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

C# Webclient Stream download file from FTP to local storage(C# Webclient Stream 从 FTP 下载文件到本地存储)
本文介绍了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 下载文件到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)
Why do I get quot;error: ... must be a reference typequot; in my C# generic method?(为什么我会收到“错误:...必须是引用类型?在我的 C# 泛型方法中?)
Strange LINQ Exception (Index out of bounds)(奇怪的 LINQ 异常(索引越界))