更有效的文件写入方式
本文关键字:方式 文件 有效 | 更新日期: 2023-09-27 18:00:52
我当前正在使用以下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秒。2GB的文件传输耗时约37分钟,而预期的传输时间约为15分钟。我想确保此代码的接收端不会导致速度减慢,我想知道是否有更有效的方法将这些文件写入磁盘。
您可以尝试使用WebClient
类来获取原始文件,而不是流式块:
WebClient client = new WebClient();
client.DownloadFile(fileUri, filePathOnHardDrive);