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 下载到本地存储


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01