Use FileStream to replicate multimedia files.
The main idea of using FileStream to replicate multimedia files is to use two FileStream objects, one reading byte and the other writing bytes.
Knowledge points:
1. The File class we operate on, FileStream, StreamWriter, and StreamReader are all in the System. IO namespace.
2. the difference between File and FileStream operations is that File is equivalent to reading or writing the entire File at a time, which may increase the memory burden, with FileStream, you can specify the number of bytes of the operation when reading or writing data (a bit similar to the paging query effect of the database), thus reducing the memory overhead. (Another File is a static class. FileStream, StreamWriter, and StreamReader are non-static classes ).
3. The difference between FileStream and StreamWriter and StreamReader is that StreamWriter and StreamReader can only operate text files, while FileStream can operate both text files and multimedia files.
4. After the FileStream, StreamWriter, and StreamReader classes are used, we must manually call the Close () and Dispose () methods because GC cannot clean up the garbage generated by them.
5. If the class (or base class) implements the IDisposable interface, we can use the using syntax to automatically clear the garbage they produce without calling the Close () and Dispose () methods. Common classes include SqlConnection in ado.net, SqlCommand, and FileStream, StreamWriter, and StreamReader in this article.
The Code is as follows:
Static void CopyFile (string source, string target) {if (! File. exists (source) {throw new Exception ("the source file does not exist");} // create a stream for reading using (FileStream sfReader = new FileStream (source, FileMode. open, FileAccess. read) {// create a stream in charge of writing using (FileStream sfWriter = new FileStream (target, FileMode. openOrCreate, FileAccess. write) {// read every 5 MB byte [] buffer = new byte [1024*1024*5]; int size = 0; do {// The returned size is the actual number of bytes read, which may be 5 MB or smaller than 5 M size = sfReader. read (buffer, 0, buffer. Length); // The last parameter is the actual number of bytes rather than 5 MB. // If the size is changed to buffer. Length here, when the actual number of bytes is less than 5 MB, there will be very blank bytes. SfWriter. Write (buffer, 0, size);} while (size! = 0);} // using, so when the program runs here, the sfWriter resources are automatically released, and no need to manually call Dispose ()};}View Code
Call Method
// Use FileStream to copy a multimedia file string source = @ "C: \ Users \ Administrator \ Desktop \ source. avi "; string target = @" C: \ Users \ Administrator \ Desktop \ target. avi "; CopyFile (source, target );View Code