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

时间:2023-02-04
本文介绍了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 下载文件到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:StreamReader.ReadToEnd() 返回一个空字符串 下一篇:为什么我的新 XmlTextReader(stream) 将许多兆字节读入内存而不是正确流式传输?

相关文章

最新文章