1. Overview of Stream Class
In the .NET Framework, there is a difference between files and streams.
A file is a dataset stored on disk, with a name and corresponding path. When a file is opened and read/write to it, the file is called a stream.
However, streaming is not just an open disk file, but also network data. The .Net Framework allows creating streams in memory. Additionally, in console applications, keyboard input and text display are streams.
1. Stream class
The Stream class is an abstract base class for all streams.
The main properties of the Stream class include CanRead, CanWrite (whether it supports read and write), CanSeek (whether it supports lookup), CanTimeout (whether it can time out), Length (length of the stream), Position (get or set the position in the current stream), ReadTimeout/WriteTimeout (get or set the timeout of read and write operations)
The main methods of the Stream class include BeginRead/EndRead (start and end asynchronous read operation), BeginWrite/EndWrite (start and end asynchronous write operation), Read (read byte sequence), ReadByte (read byte), Seek (set lookup position), Write (write to byte sequence), WriteByte (write to a byte), Flush (clear all buffers of the stream and write buffer data to the basic device), Close (close the current stream).
2. FileStream, MemoryStream, BufferedStream and NetworkStream
- File Streaming ClassFileStream: Read, write, open and close files in the form of streams. In addition, it can also be used to operate other file-related operating system handles such as pipelines, standard inputs/outputs, etc.
- Memory StreamMemoryStreamClass: Used to create streams in memory to temporarily hold data, so with it there is no need to create temporary files on the hard disk. It encapsulates data into an unsigned byte sequence, which can directly perform read, write and search operations.
- Buffered streamBufferedStreamClass: It means adding the stream to the buffer first, and then performing data read/write operations. A buffer is a byte block in the memory area used to cache data. Using buffers can reduce the number of calls to the operating system when accessing data and enhance the system's read/write function.
- Network flowNetworkStreamClass: Provides the basic flow of data for network access.
Note that the FileStream class also has a buffering function. When creating an instance of the FileStream class, you only need to specify the size of the buffer.
2. File Stream Class FileStream
FileStream class FileStream exposes a file-based Stream, which supports synchronous read/write operations and asynchronous read/write operations.
The feature of the FileStream class is to manipulate byte and byte arrays. This method is not suitable for operating text files composed of character data, and is suitable for processing non-text files.
The FileStream class provides low-level and complex operations on files, so it can implement more advanced functions.
1. Read the file
Read,ReadByte()
//Create a FileStream object of d:\FileStream fstream = new FileStream(@"d:\", ); byte[] bData = new byte[]; //Set the current location of the stream as the file start position(0, ); //Save the contents of the file into a byte array (cache)(bData, 0, ); string result = Encoding.(bData); (result); if (fstream != null) { //Clear the buffer of this stream so that all buffered data is written to the file (); (); }
In addition to converting byte arrays into strings to display, byte arrays can also be used.
//1. Display as a pictureMemoryStream mstream = new MemoryStream(bData); Image img = (mstream); //2. Store as value in the databaseSqlCommand comm = new SqlCommand(); ("images", ).Value = bData; //3. Write to the file("c:\", bData); FileStream fstream = new FileStream("c:\"); (bData, 0, );
2. Read files in chunks
int bufferSize = 5; //Create a FileStream object of d:\FileStream fstream = new FileStream(@"d:\", , , , bufferSize, false);//false means synchronous readingbyte[] bData = new byte[bufferSize]; //Set the current location of the stream as the file start position(0, ); int bytesRead; do { //Save the contents of the file into a byte array (cache) bytesRead = (bData, 0, ); string result = Encoding.(bData, 0, bytesRead); (result); } while (bytesRead > 0); if (fstream != null) { //Clear the buffer of this stream so that all buffered data is written to the file (); (); }
3. Read files asynchronously
ManualResetEvent mEvent = new ManualResetEvent(false); int bufferSize = 5; byte[] bData = new byte[bufferSize]; FileStream fstream = new FileStream(@"d:\", , , , bufferSize, true);//false means asynchronous reading AsyncCallback callback = null; callback = (IAsyncResult ar) => { int bytesRead = (ar); (Encoding.(bData, 0, bytesRead)); if (bytesRead > 0) { (bData, 0, bufferSize, callback, null);//Continue reading } else { (); ();//Reading is completed, send the signal } }; IAsyncResult async = (bData, 0, bufferSize, callback, null); (5000, false); ("Read Completed");
Note: Members of the IAsyncResult interface
AsyncState Gets a user-defined object that qualifies or contains information about asynchronous operations.
AsyncWaitHandle Gets the WaitHandle used to wait for the asynchronous operation to complete.
CompletedSynchronously Gets a value indicating whether the asynchronous operation is completed synchronously.
IsCompleted Gets a value indicating whether the asynchronous operation has been completed.
4. Write a document
Write,WriteByte(Byte)
//Create a FileStream object of d:\FileStream fstream = new FileStream(@"d:\", ); byte[] bData = Encoding.("test filestream"); //Set the current location of the stream as the file start position(0, ); //Write the contents of the byte array to the file(bData, 0, ); if (fstream != null) { //Clear the buffer of this stream so that all buffered data is written to the file (); (); }
3. MemoryStream MemoryStream Class
Memory streams have stream-specific characteristics relative to byte arrays, and their capacity can automatically grow.
In situations such as data encryption and cache data of varying lengths, it is more convenient to use memory streams.
The following code example demonstrates how to read and write data that uses memory as back-store storage.
int count; UnicodeEncoding uniEncoding = new UnicodeEncoding(); //Create data to be written to the streambyte[] firstString = ("Invalid file path characters are: "); byte[] secondString = (()); using (MemoryStream memStream = new MemoryStream(100)) { // Write the first string to the stream. (firstString, 0, ); // Write the second string to the stream by bytes. count = 0; while (count < ) { (secondString[count++]); } // Write stream properties to the console. ("Capacity = {0}, Length = {1}, Position = {2}\n", (), (), ()); // Set position to the beginning of the stream. (0, ); // Read the first 20 bytes from the stream. byte[] byteArray = new byte[]; count = (byteArray, 0, 20); // Read the remaining bytes one by one. while (count < ) { byteArray[count++] = (()); } // Decode the byte array into a char array and write it to the console. char[] charArray = new char[(byteArray, 0, count)]; ().GetChars(byteArray, 0, count, charArray, 0); (charArray); }
The difference between ToArray() and GetBuffer():
//Copying the data in the stream into a byte[] is slightly slower than GetBuffer(), but it will not put useless empty data into the buffer.byte[] byteArray = (); //Pass the reference of the Buffer in the stream, which is faster. The size of the Buffer is determined by the Capacity of the stream, but it will pass useless empty data.byte[] byteArray = ();
This is all about C#'s article using file stream FileStream and memory stream MemoryStream to operate the underlying byte array byte[]. I hope it will be helpful to everyone's learning and I hope everyone will support me more.