如何将文件从MemoryStream上传到FTP服务器

时间:2019-05-07 07:36:20

标签: c# .net ftp webclient memorystream

我创建了一个简单的应用程序,该应用程序收集表单数据,在内存中作为MemoryStream对象生成XML,然后使用SMB将XML传送到服务器。对于SMB,传递方法很简单:

var outputFile = new FileStream($@"{serverPath}\{filename}.xml", FileMode.Create);
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = stream.Read(buffer, 0, Length);

while (bytesRead > 0)
{
    outputFile.Write(buffer, 0, bytesRead);
    bytesRead = stream.Read(buffer, 0, Length);
}

但是,我需要使用FTP(带有凭据)创建替代的传送方法。我不想重写我的XML方法,因为在内存中创建它可以节省写入磁盘的工作,这在过去是我们环境中的一个问题。

我还没有找到任何示例(对于一个编码能力非常有限的人)来说明如何完成这样的事情。

通常,当我需要将文件上传到FTP服务器时,我会使用类似这样的内容:

using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential("user", "pass");
    client.UploadFile(uri, WebRequestMethods.Ftp.UploadFile, filename.xml);
}

这可以适合从MemoryStream上传而不是从磁盘上的文件上传吗? 如果没有,我可以通过其他什么方式将MemoryStream上传到FTP服务器?

2 个答案:

答案 0 :(得分:1)

请使用FtpWebRequest,如您在Upload a streamable in-memory document (.docx) to FTP with C#?中所见:

WebRequest request = WebRequest.Create("ftp://ftp.example.com/remote/path/filename.xml");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
using (Stream ftpStream = request.GetRequestStream())
{
    memoryStream.CopyTo(ftpStream);
}

或使用WebClient.OpenWrite(您也可以在@Neptune的答案中看到):

using (var webClient = new WebClient())
{
    const string url = "ftp://ftp.example.com/remote/path/filename.xml";
    using (Stream uploadStream = client.OpenWrite(url))
    {
        memoryStream.CopyTo(uploadStream);
    }
}

等效地,您现有的FileStream代码可以简化为:

using (var outputFile = new FileStream($@"{serverPath}\{filename}.xml", FileMode.Create))
{
    stream.CopyTo(outputFile);
}

尽管显然,更好的方法是避免使用中间的MemoryStream并将XML直接写入FileStreamWebRequest.GetRequestStream(使用它们共同的Stream接口)。

答案 1 :(得分:1)

您可以使用方法OpenWrite / OpenWriteAsync获取可从任何源(流/数组/ ...等)写入的流。 这是一个使用OpenWriteMemoryStream进行书写的示例:

var sourceStream = new MemoryStream();
// Populate your stream with data ...
using (var webClient = new WebClient())
{
     using (Stream uploadStream = client.OpenWrite(uploadUrl))
     {
         sourceStream.CopyTo(uploadStream);
     }
}
相关问题