问题描述
我一直通过 .net 命名空间提供的 webclient 对象从 ftp 服务器下载文件,然后通过 将字节写入实际文件>binarywriter.一切都很好.但是,现在文件的大小急剧增加,我担心内存限制,所以我想创建一个下载流,创建一个文件流,并从下载中逐行读取并写入文件.
i've been downloading files from an ftp server via the webclient object that the .net namespace provides and then write the bytes to a actual file via a binarywriter. all is good. however, now, the files have dramatically increased in size and i'm worried about memory constraints so i'd like to create a download stream, create an file stream, and line by line read from the download and write to the file.
我很紧张,因为我找不到一个很好的例子.这是我的最终结果:
i'm nervous since i couldn't find a nice example of this. here's my end result:
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());
}
}
}
我会采用这种不正确/更好的方式/等等吗?
am i going about this incorrect/better way/etc?
推荐答案
webclient 类的以下用法你试过了吗?
have you tried the following usage of webclient class?
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);
}
如果您想使用自定义缓冲区大小明确下载文件:
if you want to download file explicitly using customized buffer size:
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);
}
}
}