C# Webclient Stream 将文件从 FTP 下载到本地存储 [英] C# Webclient Stream download file from FTP to local storage

查看:30
本文介绍了C# Webclient Stream 将文件从 FTP 下载到本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于C# Webclient Stream 将文件从 FTP 下载到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆