ADVERTISEMENT
ADVERTISEMENT

C# program to demonstrate 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

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.

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.

C# Files Programs »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.