MemoryStream is located in the namespace and provides streaming read and write operations for system memory. It is often operated as an intermediate object when exchanging data of other streams.
- The MemoryStream class encapsulates a byte array. When constructing an instance, you can use a byte array as a parameter, but the length of the array cannot be adjusted. Create an instance using the default parameterless constructor, which can be written using the Write method, and the size of the array is automatically adjusted as the byte data is written.
- When reading data streams in the MemoryStream class, you can use the seek method to locate the current position of the reader, and you can read data of the specified length at one time through an array of specified lengths. The ReadByte method reads one byte at a time and returns the byte a integer value.
- The UnicodeEncoding class defines the relevant functions of UTF-16 encoding in Unicode. The method in it converts a string to bytes, or you can convert a byte to a string.
MemoryStream is a special case, there is no unmanaged resource in MemoryStream, so it doesn't matter if its Dispose is not called. Hosted resources.Net will be automatically recycled
MemoryStream inherits from the Stream class. The advantage of memory stream is that pointers can be swayed around, that is, canSeek, Position, Seek(). Read any paragraph.
It is necessary to understand the SeekOrigin enum in memory streams
Enumerate members | Member Value | describe |
---|---|---|
Begin | 0 | Specifies the beginning of the stream. |
Current | 1 | Specifies the current location within the stream. |
End | 2 | Specifies the end of the stream. |
Properties and methods provided by MemoryStream:
1. Attributes
CanRead has been rewritten. Gets a value indicating whether the current stream supports reading.
CanSeek has been rewritten. Gets a value indicating whether the current stream supports lookup.
CanTimeout Gets a value that determines whether the current stream can time out. (Inherited from Stream.)
CanWrite Rewritten. Gets a value indicating whether the current stream supports writing.
Capacity Gets or sets the number of bytes assigned to the stream. This is the allocated number of bytes
Length has been rewritten. Gets the stream length represented by bytes. This is the number of bytes that really take up.
Position rewritten. Gets or sets the current location in the stream.
ReadTimeout Gets or sets a value that determines how long the stream tries to read before timeout. (Inherited from Stream.)
WriteTimeout Gets or sets a value that determines how long the stream attempts to write before timeout. (Inherited from Stream.)
2. Method
BeginRead starts asynchronous reading operation. (Inherited from Stream.)
BeginWrite starts asynchronous write operations. (Inherited from Stream.)
Close Close the current stream and releases all resources associated with it (such as sockets and file handles). (Inherited from Stream.)
CreateObjRef Creates an object that contains all the relevant information needed to generate a proxy for communicating with a remote object. (Inherited from MarshalByRefObject.)
Dispose Reloaded.
EndRead Wait for the pending asynchronous reading to complete. (Inherited from Stream.)
EndWrite End asynchronous write operation. (Inherited from Stream.)
Flush has been rewritten. Rewrite so that nothing is done.
GetBuffer Returns an unsigned byte array from which this stream was created. It will return all allocated bytes, and it will not work.
GetLifetimeService retrieves the current lifetime service object that controls the lifetime policy of this instance. (Inherited from MarshalByRefObject.)
InitializeLifetimeService Gets the lifetime service object that controls the lifetime policy of this instance. (Inherited from MarshalByRefObject.)
Read Rewritten. Read byte blocks from the current stream and write data into buffer. It took me a long time to understand the meaning of the Read() method. The first parameter is the byte array to be output to the read content, the second parameter is the offset placed in the first parameter, that is, the position of the array to be output, and the third parameter is the number of characters to be read. In this method, you can read any piece of memory you need. Note that the Read() method starts reading from the Position property of the current stream. This is why many people cannot read the content when they test the data that has just been written into memory, because after just writing into memory, the position happens to be at the last bit. Of course, the Read() method cannot be read. The powerful thing about this method is that you can read out a fragment you want from a memory stream.
ReadByte has been rewritten. Read a byte from the current stream.
Seek Rewritten. Sets the position in the current stream to the specified value.
SetLength has been rewritten. Sets the length of the current stream to the specified value.
Synchronized Creates a thread-safe (synchronized) wrapper around the specified Stream object. (Inherited from Stream.)
ToArray Writes the entire stream content to a byte array, regardless of the Position property.
Write has been rewritten. Write a byte block to the current stream using data read from the buffer. Note also that the second parameter is the offset of the first parameter array.
WriteByte has been rewritten. Writes a byte to the current position in the current stream.
WriteTo Write the entire content of this memory stream to another stream.
The following is a sample code for use:
static void Main(string[] args) { //Properties test MemoryStream ms = new MemoryStream(); (); //True Memory stream is readable (); //True Memory flow supports search, pointers are moved around and searched. (); //False memory stream does not support timeout (); //True Memory stream is writable (); //0 Number of bytes assigned to the stream byte[] bytes = Encoding.("abcdedcba"); (bytes, 0, ); //A piece of text has been written to memory (); //256 Read again the number of bytes allocated for the text stream has become 256. It seems that the memory stream is allocated according to the amount needed. (); //9 This is the stream length, usually the same as the number of characters in English, the number of bytes it really takes. (); //9 The current location of the stream, this property is readable and set //(); Since the stream does not support timeout, this property will report an error if read or set //(); Since the stream does not support timeout, this property will report an error if read or set //Method test byte[] byte1 = (); //Return to an unsigned byte array. I was almost fooled. The unsigned byte array is actually byte(0~255), and the signed byte sbyte(-128~127) string str1 = Encoding.(byte1); (str1); //Output abcdedcba (2, ); //Set the position where the current stream is reading. It is the starting position that starts from 0. //Read a byte from memory int i = (); (i); //Output 99 byte[] bytes3 = (); foreach (byte b in bytes3) { (b + "-");//For comparison output 97-98-99-100-101-100-99-98-97- You can see that the second digit 0,1,2 happens to be 99 } MemoryStream ms2 = new MemoryStream(); byte[] bytes6 = Encoding.("abcde"); (bytes6, 0, ); (); //Output 5 After writing, the stream position reaches the end, so if you want to read it with read, you must add the following line of code. //(0, ); //If you want to use the Read method to read the complete stream, you must set the current position. Read starts reading from the Position position. = 0; //Read starts reading from the current position, and this line of code means the same as the above line. byte[] byteArray = new byte[5] { 110, 110, 110, 110, 110 }; //99 is after YTF8 decoding, n (byteArray, 2, 1); //Read a byte, in the first element of byteArray, (note that it starts from 0) (Encoding.(byteArray)); //nnann //(byteArray, 2, 2); //(Encoding.(byteArray)); //nnabn // When the total length of the received array is exceeded, the subsequent elements will be removed. //Set the length of the current stream (); //Output 9 The current stream length is 9 (20); (); //Output 20 foreach (byte b in ()) //Convert the content of the stream, that is, the content in memory, to convert the byte array { (b + "-"); //Output 97-98-99-100-101-100-99-98-97-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0 Since the length is set, the empty automatically fills 0 } (Encoding.(())); //Output abcdedcba Although the length has become longer, it does not affect the reading of data. MemoryStream ms1 = new MemoryStream(); byte[] bytes4 = (); ("This memory stream does not write data(Write)" + Encoding.(bytes4));//Output This memory stream does not write data (Write) because the memory is empty // Let's write a specified location below MemoryStream ms3 = new MemoryStream(); byte[] bytesArr = ("abcdefg"); (bytesArr, 0, ); = 2; (97); //97 represents a. This code means that the original second c is replaced by a. string str = (()); (str); //Output abacdefg byte[] byteArr1 = ("kk"); = 4; (byteArr1, 0, ); (Encoding.(())); //abadkkg //Replace two bytes from bit 4 to KK (); }
Next, implement the conversion of the data class:
using ; using ; using ; public class DataSwitch { /// <summary> /// Convert data class objects into byte streams /// </summary> /// <param name="obj"></param> /// <returns></returns> /// //MemoryStream: Creates a stream whose supported storage area is memory. //IFormatter: Provides the function of formatting serialized objects. public static byte[] ObjectToBytes(object obj) { using (MemoryStream ms = new MemoryStream()) { // //Serialize and deserialize objects or entire connection objects in binary format. IFormatter formatter = new BinaryFormatter(); //Put the string into memStream in binary (ms, obj); //Returns the unsigned byte array from which this stream is created. It will return all allocated bytes, and it will not work. Return an unsigned byte array ,Unsigned byte array Actually it'sbyte(0~255),Signed bytessbyte(-128~127) return (); } } /// <summary> /// Bytes are transferred to data-class objects /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static object BytesToObject(byte[] bytes) { using (MemoryStream ms = new MemoryStream(bytes)) { // //Serialize and deserialize objects or entire connection objects in binary format. IFormatter formatter = new BinaryFormatter(); //Put the string into memStream in binary return (ms); } } }
This is the end of this article about the detailed explanation of C# MemoryStream class case. For more related C# MemoryStream content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!