C#Webclient Stream将文件从FTP下载到本地存储

时间:2012-08-16 19:53:25

标签: c# ftp stream webclient

我一直在通过WebClient命名空间提供的.NET对象从FTP服务器下载文件,然后通过BinaryWriter将字节写入实际文件。一切都很好。但是,现在,文件的大小已经大大增加,我担心内存限制,所以我想创建一个下载流,创建一个文件流,逐行读取下载并写入文件。< / p>

我很紧张,因为我找不到一个很好的例子。这是我的最终结果:

var request = new WebClient();

// Omitted code to add credentials, etc..

var downloadStream = new StreamReader(request.OpenRead(ftpFilePathUri.ToString()));
using (var writeStream = File.Open(toLocation, FileMode.CreateNew))
{
    using (var writer = new StreamWriter(writeStream))
    {
        while (!downloadStream.EndOfStream)
        {
            writer.Write(downloadStream.ReadLine());                  
        }
    }
}

我是否会采用这种不正确/更好的方式/等?

1 个答案:

答案 0 :(得分:8)

您是否尝试过WebClient类的以下用法?

using (WebClient webClient = new WebClient())
{
    webClient.DownloadFile("url", "filePath");
}

<强>更新

using (var client = new WebClient())
using (var stream = client.OpenRead("..."))
using (var file = File.Create("..."))
{
    stream.CopyTo(file);
}

如果要使用自定义缓冲区大小显式下载文件:

public static void DownloadFile(Uri address, string filePath)
{
    using (var client = new WebClient())
    using (var stream = client.OpenRead(address))
    using (var file = File.Create(filePath))
    {
        var buffer = new byte[4096];
        int bytesReceived;
        while ((bytesReceived = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            file.Write(buffer, 0, bytesReceived);
        }
    }
}