我一直在通过.NET
命名空间提供的WebClient
对象从FTP服务器下载文件,然后通过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());
}
}
}
我是否要采取这种不正确/更好的方法/等?
您是否尝试过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);
}
}
}