The common MemoryStream constructors have the following 3 types.
1:memorystream () The initial allocation capacity of this constructor is 0 bytes, and its capacity can be extended automatically as data is written continuously. This form is generally applied when the data content size is not determined.
2:memorystream (byte[]) is different from the parameterless constructor of MemoryStream, and the MemoryStream instance of the constructor is initialized based on byte arrays of type Byte, and the capacity size of the instance is fixed to the length of the byte array. Because the capacity of an instance cannot be extended, this constructor is typically used where the data is not changed.
3:memorystream (int capacity) Creates an instance of the initial capacity size of capacity by this constructor. And the instance capacity size can be expanded.
The complete code is as follows:
Introduce a namespace:
using System.IO;
Full code:
Namespace Memorystreamapp { class program { static void Main (string[] args) { // Constructs the MemoryStream instance and outputs the initial allocation capacity and uses the size MemoryStream mem = new MemoryStream (); Console.WriteLine ("Initial allocation capacity: {0}", mem.) capacity); Console.WriteLine ("Initial usage: {0}", mem.) Length); Converts the data to be written from a string to a byte array unicodeencoding encoder = new UnicodeEncoding (); byte[] bytes = encoder. GetBytes ("new data"); Writes data to the memory stream for (int i = 1; i < 4; i++) { Console.WriteLine ("{0} times write new data", I); Mem. Write (bytes, 0, bytes. Length); } The capacity and usage size of the MemoryStream instance after the data is written Console.WriteLine ("Currently allocated capacity: {0}", Mem. capacity); Console.WriteLine ("Current usage: {0}", mem.) Length); Console.ReadLine ();}}}
The program run Effect:
C # uses MemoryStream to write data to memory