【问题标题】:Upload a streamable in-memory document (.docx) to FTP with C#?使用 C# 将可流式内存文档 (.docx) 上传到 FTP?
【发布时间】:2018-05-10 01:45:39
【问题描述】:

我正在尝试将MemoryStream 中的 .docx 文件上传到 FTP

但是上传完成后,文件是空的。

MemoryStream mms = new MemoryStream();
document2.SaveToStream(mms, Spire.Doc.FileFormat.Docx);

string ftpAddress = "example";
string username = "example";
string password = "example";

using (StreamReader stream = new StreamReader(mms))
{
    // adnu is a random file name.
    WebRequest request =
        WebRequest.Create("ftp://" + ftpAddress + "/public_html/b/" + adnu + ".docx");
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(username, password);
    Stream reqStream = request.GetRequestStream();
    reqStream.Close();
}

【问题讨论】:

    标签: c# .net ftp ftpwebrequest spire.doc


    【解决方案1】:

    将文档直接写入请求流。使用中间 MemoryStream 毫无意义。 StreamReader/StreamWriter 用于处理文本文件,而.docx 是二进制文件格式,所以也不要使用它们。

    WebRequest request =
        WebRequest.Create("ftp://ftp.example.com/remote/path/document.docx");
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(username, password);
    using (Stream ftpStream = request.GetRequestStream())
    {
        document2.SaveToStream(ftpStream, Spire.Doc.FileFormat.Docx);
    }
    

    或者使用WebClient.OpenWrite:

    using (var webClient = new WebClient())
    {
        const string url = "ftp://ftp.example.com/remote/path/document.docx";
        using (Stream uploadStream = client.OpenWrite(url))
        {
            document2.SaveToStream(uploadStream, Spire.Doc.FileFormat.Docx);
        }
    }
    

    你只需要一个中间的MemoryStream,如果Spire库需要一个可搜索的流,FtpWebRequest.GetRequestStream返回的Stream不是。我无法测试。

    如果是这样,请使用:

    MemoryStream memoryStream = new MemoryStream();
    document2.SaveToStream(memoryStream, Spire.Doc.FileFormat.Docx);
    
    memoryStream.Seek(0, SeekOrigin.Begin);
    
    WebRequest request =
        WebRequest.Create("ftp://ftp.example.com/remote/path/document.docx");
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(username, password);
    using (Stream ftpStream = request.GetRequestStream())
    {
        memoryStream.CopyTo(ftpStream);
    }
    

    或者同样,您可以像前面的示例一样使用WebClient.OpenWrite

    另见类似问题Zip a directory and upload to FTP server without saving the .zip file locally in C#

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 2012-08-27
      • 1970-01-01
      • 2011-02-09
      相关资源
      最近更新 更多