使用 C# 将可流式存储的内存中文档 (.docx) 上传到 FTP?

Upload a streamable in-memory document (.docx) to FTP with C#?

我正在尝试将 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();
}

将文档直接写入请求流。使用中间 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);
    }
}

如果 Spire 库需要一个可搜索的流,您将只需要一个中间 MemoryStream,而 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#