C# Webclient Stream download file from FTP to local storage(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 下载到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# Webclient Stream 将文件从 FTP 下载到本地存储
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01