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

Upload a streamable in-memory document (.docx) to FTP with C#?(使用 C# 将可流式内存中文档 (.docx) 上传到 FTP?)

本文介绍了使用 C# 将可流式内存中文档 (.docx) 上传到 FTP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to upload a .docx file which is in MemoryStream to FTP

但上传完成后,文件为空.

But when upload is completed, the file is empty.

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 是二进制文件格式,因此也不要使用它们.

Write the document directly to the request stream. There's no point using an intermediate MemoryStream. And StreamReader/StreamWriter are for working with text files, while a .docx is a binary file format, so do not use those either.

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是什么不是.我无法测试.


You will only need an intermediate MemoryStream, if the Spire library requires a seekable stream, what the Stream returned by FtpWebRequest.GetRequestStream is not. I cannot test that.

如果是这样,请使用:

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.

Or again, you can use WebClient.OpenWrite as in the previous example.

另请参阅类似问题压缩目录并上传到 FTP 服务器,而无需在 C# 中本地保存 .zip 文件.

这篇关于使用 C# 将可流式内存中文档 (.docx) 上传到 FTP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 C# 将可流式内存中文档 (.docx) 上传到 FTP?

基础教程推荐