Q:

C# program to demonstrate MemoryStream class

belongs to collection: C# Files Programs

0

C# program to demonstrate MemoryStream class

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# program to get the size of a specified folder i... >>
<< C# program to read data from file character by cha...