C#Webclient Stream从FTP下载文件到本地存储
问题描述:
我一直在通过WebClient
对象从FTP服务器下载文件.NET
命名空间提供,然后通过BinaryWriter
将字节写入实际文件。一切都很好。但是,现在,文件的大小已经大大增加,我担心内存限制,所以我想创建一个下载流,创建一个文件流,并从下载中逐行读取并写入文件。C#Webclient Stream从FTP下载文件到本地存储
我很紧张,因为我找不到一个很好的例子。这是我的最终结果:
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());
}
}
}
我会谈论这种不正确/更好的方式/ etc?
答
您是否尝试过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);
}
}
}
是的,仍然是(请求对象是Web客户端[I” m更新我的帖子来显示这个明确]),但DownladFile会给我在内存中的整个文件 - 与我正在寻找的相反.. – OnResolve 2012-08-16 19:58:32
@OnResolve,对不起,我没有提及。请参阅更新。 – 2012-08-16 20:03:43
@OnResolve,我已经添加了具有自定义缓冲区大小的版本。 – 2012-08-16 20:12:28