FileStream buffers read and write to improve performance. Copy a small segment of the file at a time to save the total memory overhead. Of course, native replication can also be used in .NET.
When FileStream reads a file, it first talks about exile into memory, and writes data in memory (buffered) to the file after Flash() method. If the file is very large, it will inevitably consume performance. Special package in FileHelper for emergencies. If the file is large, such as 4G, it will overflow, and the result of copying bytes is seriously lost, resulting in different sizes of the copied file and the source file. The code modified here is as follows:
public static class FileHelper { /// <summary> /// Copy large files /// </summary> /// <param name="fromPath">Path of source file</param> /// <param name="toPath">Path to save the file</param> /// <param name="eachReadLength">Length per read</param> /// <returns>Whether the copy is successful</returns> public static bool CopyFile(string fromPath, string toPath, int eachReadLength) { //Read the source file into a file stream FileStream fromFile = new FileStream(fromPath, , ); //Appended method to write to file stream FileStream toFile = new FileStream(toPath, , ); //The actual length of the file read int toCopyLength = 0; //If the length of each read is less than the length of the source file, read in segments if (eachReadLength < ) { byte[] buffer = new byte[eachReadLength]; long copied = 0; while (copied <= - eachReadLength) { toCopyLength = (buffer, 0, eachReadLength); (); (buffer, 0, eachReadLength); (); //The current location of the stream = ; copied += toCopyLength; } int left = (int)( - copied); toCopyLength = (buffer, 0, left); (); (buffer, 0, left); (); } else { //If the length of the file copied each time is greater than the length of the source file, copy the actual file length directly byte[] buffer = new byte[]; (buffer, 0, ); (); (buffer, 0, ); (); } (); (); return true; } }
Test code:
class Program { static void Main(string[] args) { Stopwatch watch = new Stopwatch(); (); if ((@"D:\Installation File\New Folder\SQLSVRENT_2008R2_CHS.iso", @"F:\SQLSVRENT_2008R2_CHS.iso", 1024 * 1024 * 5)) { (); ("Copying is completed, time-consuming:" + + "Second"); } (); } }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.