繁体   English   中英

C#Webclient流将文件从FTP下载到本地存储

[英]C# Webclient Stream download file from FTP to local storage

我一直在通过.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);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM