6

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

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

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());                  
        }
    }
}

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

4

1 回答 1

9

您是否尝试过以下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);
        }
    }
}
于 2012-08-16T19:57:04.047 回答