. Net stream-use stream for file replication,. net flow
Similar to various file streams and network streams in Java,. net also has various types of streams. The main purpose of a stream is to interact with files or data sources outside the application. The base class is Stream, which is defined in the namespace System. IO;
1. Use a stream for one-time copy and write
First, we create a test file on the desktop and write something:
The following is our code:
# Region uses a stream for one-time copying // creates a file stream object (parameter 1: Specifies the file location; parameter 2: enumeration value, specifying the way the operating system opens the file; parameter 3: indicates the intention to open the file. Note that the second and third parameters must be used together.) Stream source = new FileStream (@ "C: /Users/v-liuhch/Desktop/StreamTest.txt ", FileMode. open, FileAccess. read); byte [] buffer = new byte [source. length]; // write the file data to the byte array (parameter 1: The byte array to be written; parameter 2: used to set the position where the file is read; parameter 3: number of bytes read) int byteRead = source. read (buffer, 0, (int) source. length); // The returned value is the number of bytes read. // foreach (var B in buffer) // {// Console. writeLine (Convert. toString (B, 2); // binary // Console. writeLine (Convert. toString (B, 10); // decimal // Console. writeLine (Convert. toString (B, 16 ). toUpper (); // hexadecimal //} // Console. readKey (); // write the file to 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 that if you do not use using, do not forget dispose.
2. Cyclic and batch Replication
To test the following code, it is recommended to find a large file.
# Region cyclic and batch copy/* problem Background: transfer a larger file; * The file size cannot be known in advance, for example, reading a network file; * In the above case, you cannot create a byte [] array with the proper size. At this time, you can only read and write data in batches. only part of the bytes are read at a time until the end of the file. */int BufferSize = 10240; // 10KB using (Stream source = new FileStream (@ "C:/Users/v-liuhch/Desktop/sherlock. wmv ", FileMode. open, FileAccess. read) {using (Stream target = new FileStream (@ "C:/Users/v-liuhch/Desktop/sherlockCopy. wmv ", FileMode. create, FileAccess. write) {byte [] buffer = new byte [BufferSize]; int bytesRead; do {bytesRead = source. read (buffer, 0, BufferSize); target. write (buffer, 0, bytesRead);} while (bytesRead> 0);} # endregion
PS: using is recommended;
It is still relatively scientific to split and read large files, similar to the principle of uploading large files.