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

查看:274
本文介绍了使用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);
    }
}






如果Spire库需要可查找的流,则只需要一个中间 MemoryStream ,<$ c返回的 Stream c $ c> FtpWebRequest.GetRequestStream 不是。我无法测试。


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.

如果是这种情况,请使用:

If that's the case, use:

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服务器,而无需将.zip文件本地保存在C#中。

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆