// create a new memory stream var stream = new MemoryStream(); // write some data to the stream var data = Encoding.UTF8.GetBytes("Hello, world!"); stream.Write(data, 0, data.Length); // read the data from the stream stream.Position = 0; var buffer = new byte[1024]; var bytesRead = stream.Read(buffer, 0, buffer.Length); var message = Encoding.UTF8.GetString(buffer, 0, bytesRead); // output the data Console.WriteLine(message);
// create a memory stream from an existing byte array var data = new byte[] { 0x01, 0x02, 0x03, 0x04 }; var stream = new MemoryStream(data); // read some data from the stream var buffer = new byte[2]; var bytesRead = stream.Read(buffer, 0, buffer.Length); // output the data foreach (var b in buffer) { Console.WriteLine(b); }This example creates a new MemoryStream from an existing byte array, reads some data from the stream, and outputs it to the console. It uses a foreach loop to iterate over the bytes in the buffer and output them individually. The MemoryStream class is part of the System.IO namespace in .NET, which is included in the .NET Framework and .NET Core libraries.