我一直在通过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());
}
}
}
我是否会采用这种不正确/更好的方式/等?
答案 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);
}
}
}