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

后端 未结 8 1675
悲&欢浪女
悲&欢浪女 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);
                }
           }
        }
    
    0 讨论(0)
  • 2020-11-27 05:31

    Mark Russinovich would be the authority on this.

    He wrote on his blog an entry Inside Vista SP1 File Copy Improvements which sums up the Windows state of the art through Vista SP1.

    My semi-educated guess would be that File.Copy would be most robust over the greatest number of situations. Of course, that doesn't mean in some specific corner case, your own code might beat it...

    0 讨论(0)
提交回复
热议问题