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

时间:2017-11-26 20:01:36

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

我正在尝试将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(); } 中的.docx文件上传到FTP

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

(nX,nY,nZ)

1 个答案:

答案 0 :(得分:0)

将文档直接写入请求流。使用中间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库需要可搜索的流,那么您只需要一个中间MemoryStreamStream返回的FtpWebRequest.GetRequestStream不是。{1}}。我无法测试。

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

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#