gpt4 book ai didi

c# - 更有效的写入文件的方法

转载 作者:太空宇宙 更新时间:2023-11-03 21:32:55 25 4
gpt4 key购买 nike

我目前正在使用以下 C# 代码从 C++ 服务器传输文件

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace WebRequestTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Making small binary request: 1MB");
makeRequest("http://server:8081/sm_binary", "sm_copied");

Console.WriteLine("Making medium binary request: 10MB");
makeRequest("http://server:8081/md_binary", "md_copied");

Console.WriteLine("Making large binary request: 100MB");
makeRequest("http://server:8081/lg_binary", "lg_copied");

Console.WriteLine("Making huge binary request: 2GB");
makeRequest("http://server:8081/hg_binary", "hg_copied");


while (true) { }
}

static void makeRequest(string url, string filename)
{
Console.WriteLine("Starting request: " + DateTime.Now.ToString("HH-mm-ss-fff"));
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();

Console.WriteLine("Starting file write: " + DateTime.Now.ToString("HH-mm-ss-fff"));
using (System.IO.FileStream fs = System.IO.File.Create("./Binaries/" + filename))
{

byte[] buffer = new byte[8 * 1024];
int len;
while ((len = data.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, len);
}

fs.Close();
}

Console.WriteLine("Process is done: " + DateTime.Now.ToString("HH-mm-ss-fff") + "\n");
}
}
}

前三个文件传输的时间合理,100MB 传输和写入大约需要 43 秒。与预期的约 15 分钟相比,2GB 文件传输耗时约 37 分钟,长得令人讨厌。我想确保此代码的接收端不会导致速度下降,我想知道是否有更有效的方法将这些文件写入磁盘。

最佳答案

您可以尝试使用 WebClient class 而不是获取原始文件而不是流式 block :

WebClient client = new WebClient();
client.DownloadFile(fileUri, filePathOnHardDrive);

关于c# - 更有效的写入文件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23389068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com