The main idea of using FileStream to realize multimedia file copying is to use two FileStream objects, one to read bytes and the other to write bytes.
Knowledge points involved:
1. The file class that we usually manipulate, filestream,streamwriter,streamreader, is under the System.IO namespace.
the difference between the 2.File class and the FileStream class action file is that file is equivalent to a one-time read or write to the entire file, which may increase the memory burden, while using FileStream can specify the number of bytes of the operation at read or write ( somewhat similar to the effect of a database paging query ), which reduces the overhead of memory. (another file is a static class, and Filestream,streamwriter,streamreader is a non-static class).
The difference between 3.FileStream and Streamwriter,streamreader is that Streamwriter,streamreader can only manipulate text files, and FileStream can manipulate both text files and multimedia files.
After each use of the 4.filestream,streamwriter,streamreader class, because the GC cannot clean up their resulting garbage, we must call the close (), Dispose () method manually.
5. If the class (or base class) implements the IDisposable interface, then we can use the using syntax to automatically clean up the garbage they generate without calling the close (), Dispose () method. Common classes such as the Sqlconnection,sqlcommand class in ADO and the Filestream,streamwriter,streamreader class in this article.
The code is as follows
Static voidCopyFile (stringSourcestringtarget) { if(!file.exists (source)) { Throw NewException ("source file does not exist"); } //Create a stream that is responsible for reading using(FileStream Sfreader =NewFileStream (source, FileMode.Open, FileAccess.Read)) { //Create a stream that is responsible for writing using(FileStream Sfwriter =NewFileStream (Target, FileMode.OpenOrCreate, FileAccess.Write)) { //5M size per read byte[] buffer =New byte[1024x768*1024x768*5]; intSize =0; Do { //the size returned is the actual number of bytes read, which may be equal to 5M or less than 5MSize = Sfreader.read (buffer,0, buffer. Length); //the last parameter is the actual number of bytes, not 5M. //If the size is changed to buffer here. Length, when the actual number of bytes is less than 5M, there will be a very empty byte padding. Sfwriter.write (Buffer,0, size); } while(Size! =0); }//using the function, so when the program executes here, it will automatically release Sfwriter resources without manually calling Dispose () }; }
View Code
Invocation mode
// using FileStream to realize multimedia file copying string @" C:\Users\Administrator\Desktop\source.avi " ; string @" C:\Users\Administrator\Desktop\target.avi " ; CopyFile (source, target);
View Code
Using FileStream to realize multimedia file copying