like various file streams in Java, network streams are similar, and there are various types of streams in. Net. The primary purpose of a stream is to interact with the files or data sources outside the application. The base class is stream, defined under namespace System.IO;
One, single-use stream for copy-once writes
First we build a test file on the desktop and write something:
after that is our code:
#region use stream for one-time copy//create a file stream object (parameter one: Specify the location of the file, parameter two: enumeration value, specify how the operating system opens the file; parameter three: Indicates the intention to open the file; Note the second parameter and the third parameter should be used with caution) Stream Source = new FileStream (@ "C:/users/v-liuhch/desktop/streamtest.txt", FileMode.Open, FileAccess.Read); byte[] buffer = new Byte[source. Length]; Writes the file data to a byte array (parameter one: An array of bytes to be written; parameter two: used to set where the file starts reading; parameter three: number of bytes read) int byteread = source. Read (buffer, 0, (int) source. LENGTH);//The return value is the number of bytes read//foreach (var b in buffer)//{////Console.writeli NE (convert.tostring (b, 2));//binary////console.writeline (convert.tostring (b, 10));//decimal// Console.WriteLine (convert.tostring (b, 16). ToUpper ());//hex//}//console.readkey (); Writes a file to the StreamTarget.txt using Stream target = new FileStream (@ "C:/users/v-liuhch/desktop/streamtarget.txt" , FileMode.Create, FileAccess.Write)) { Target. Write (buffer, 0, buffer. Length); } source. Dispose (); #endregion
Note If you do not use the using, do not forget Dispose.
Second, cyclic batch replication
in order to test this code, it is recommended to find a larger file what drops.
#region cyclic Batch Copy/* Issue background: pass a larger file; * The size of the file can not be known in advance, such as reading network files; * The above situation cannot create a byte[] array of exactly the right size, which can only be read and written in batches at a time until the end of the file; /int buffersize = 10240;//10KB using (Stream Source = new FileStream (@ "c:/users/v-liuhch/desktop/s Herlock.wmv ", FileMode.Open, FileAccess.Read)) {using (Stream target = new FileStream (@" C:/user S/v-liuhch/desktop/sherlockcopy.wmv ", FileMode.Create, FileAccess.Write)) {byte[] Buffe r = new Byte[buffersize]; int bytesread; do {bytesread = source. Read (buffer, 0, buffersize); Target. Write (buffer, 0, bytesread); } while (Bytesread > 0); }} #endregion
PS: It is recommended to use using;
The way to take a split reading of large files is still relatively scientific, similar to the principle of uploading large files.
The above is the. NET stream-the content that uses the stream to copy files, more relevant content please follow topic.alibabacloud.com (www.php.cn)!