Home »
.Net »
C# Programs
C# program to demonstrate the MemoryStream class
Here, we are going to learn about the MemoryStream class and demonstrating the example of MemoryStream class in C#.
Submitted by Nidhi, on September 19, 2020
C# MemoryStream Class Example
Here, we will create an object of MemoryStream class and write bytes into the memory stream using Write() and WriteByte() method then we reset the read pointer to the beginning and read byte array from the memory stream.
C# program to write bytes into the memory stream using Write() and WriteByte() methods
The source code to demonstrate the MemoryStream class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to demonstrate memory stream class.
using System;
using System.IO;
using System.Text;
class Demo
{
static void Main()
{
MemoryStream memoryStream;
int count=0;
byte[] byteArray;
byte[] byteBuff1 = { 65, 67, 68 };
byte[] byteBuff2 = { 69, 70, 71 };
memoryStream = new MemoryStream(50);
memoryStream.Write(byteBuff1, 0, 3);
while (count < byteBuff2.Length)
{
memoryStream.WriteByte(byteBuff2[count++]);
}
memoryStream.Seek(0, SeekOrigin.Begin);
byteArray = new byte[memoryStream.Length];
count = memoryStream.Read(byteArray, 0, byteArray.Length);
memoryStream.Close();
Console.WriteLine("Data written into memory stream:");
foreach (byte b in byteArray)
{
Console.Write((char)b);
}
Console.WriteLine();
}
}
Output
Data written into memory stream:
ACDEFG
Press any key to continue . . .
Explanation
Here, we created a class Demo that contains the Main() method. In the Main() method, we created an object of MemoryStream class and write bytes using Write() and WriteByte() method then reset the read pointer to the beginning of the memory stream and then read byte array from the memory stream using Read() method and print character corresponding to each byte value by character typecasting on the console screen.
C# Files Programs »