File.Copy vs. Manual FileStream.Write For Copying File

后端 未结 8 1836
悲&欢浪女
悲&欢浪女 2020-11-27 04:41

My problem is in regards file copying performance. We have a media management system that requires a lot of moving files around on the file system to different locations inc

8条回答
  •  醉梦人生
    2020-11-27 05:27

    Three changes will dramatically improve performance:

    1. Increase your buffer size, try 1MB (well -just experiment)
    2. After you open your fileStream, call fileStream.SetLength(inStream.Length) to allocate the entire block on disk up front (only works if inStream is seekable)
    3. Remove fileStream.Flush() - it is redundant and probably has the single biggest impact on performance as it will block until the flush is complete. The stream will be flushed anyway on dispose.

    This seemed about 3-4 times faster in the experiments I tried:

       public static void Copy(System.IO.Stream inStream, string outputFilePath)
        {
            int bufferSize = 1024 * 1024;
    
            using (FileStream fileStream = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                fileStream.SetLength(inStream.Length);
                int bytesRead = -1;
                byte[] bytes = new byte[bufferSize];
    
                while ((bytesRead = inStream.Read(bytes, 0, bufferSize)) > 0)
                {
                    fileStream.Write(bytes, 0, bytesRead);
                }
           }
        }
    

提交回复
热议问题