更有效的写入文件的方法

时间:2014-04-30 13:11:46

标签: c# .net webrequest

我目前正在使用以下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分钟。我想确保此代码的接收方不会导致速度减慢,我想知道是否有更有效的方法将这些文件写入磁盘。

1 个答案:

答案 0 :(得分:4)

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

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