Advertisement



< Prev
Next >



C# MemoryStream



The MemoryStream class is used to create a byte stream, which is used to write or read bytes to/from an internal array stored in the memory. The MemoryStream class is defined in the System.IO namespace.




Constructors of MemoryStream


Constructors Description
MemoryStream()
This constructor creates an object of the MemoryStream class with an internal array of an expandable capacity initialized to zero.

MemoryStream(int capacity)
This constructor creates an object of the MemoryStream class with an internal array of a size initialized to capacity.

FileStream(byte [] array)
The constructor created an object of the MemoryStream class based on the specified byte array.






Some commonly used method of MemoryStream


Methods Description
int ReadByte()
This method reads one byte from this byte stream and returns the successfully read byte.

int Read(byte[] array, int index int count)
This method reads a block of bytes from the stream and writes the data in a buffer i.e. an array of bytes, where:
  • index, represents the index position in array at which the read bytes will be placed.
  • count, represents the maximum number of bytes to read.
The method returns the total number of bytes read.

void Write()
This method write one byte to the current position in the byte stream.

void Write(byte[] array, int index int count)
This method writes a block of bytes from an array to the stream, where:
  • index, represents the starting index position in array from which the bytes will be read to write to the stream.
  • count, represents the maximum number of bytes to write.


int Seek(int offset, SeekOrigin origin)
This method sets the current position of the file pointer, where:
  • offset, represents the point relative to origin from which to begin seeking.
  • origin, represents the beginning, the end, or the current position as a reference point for offset, using a value of type SeekOrigin.
This method returns the new position of the file pointer in the stream.

void Flush()
This method closes this byte stream and also frees any resources connected with this stream.

void Close()
This method closes this byte stream and also frees any resources connected with this stream.






In this example, we are going create an object of the MemoryStream class, which creates an internal array in the memory and next, we perform write and read operations with the internal array stored in the memory, , by writing/reading a byte a time from it.

//C# Example of MemoryStream
//A program to write bytes to an internal array and to read bytes from the same internal array stored in memory


using System;
using System.IO;
using System.Text;

class A
{
public static void Main(String[] ar)
{
	try
	{
		//Creating a String object 
		String str = "Keep smiling and think positive.";
	
		//Creating a byte array from a String
		byte[] bA = Encoding.ASCII.GetBytes(str);  

		//Creating an object of MemoryStream to write to an internal array 
		//with its capacity increasing as we add bytes to it
		MemoryStream fs = new MemoryStream();

		Console.WriteLine("Writing to the internal array in memory");

		foreach(byte bt in bA)
		{
			//writing one byte at a time to the file.
			fs.WriteByte(bt);	
		}
	
		//Calling the Flush() method to flush the buffered bytes to the internal array
		fs.Flush();
		
		
		//Calling the Seek() method to set the file pointer to the beginning of the file
		fs.Seek(0, SeekOrigin.Begin);

	
		int c;
	
		//Calling the ReadByte() method to read one byte out of an internal array in memory 
		Console.WriteLine("Reading the contents of an internal array: ");
		while((c = fs.ReadByte()) !=-1) 
		{
			//Casting byte to char for displaying the read character on the screen
			Console.Write((char)c); 
		}

		//Closing the byte stream i.e. MemoryStream
		fs.Close();
	}
	catch(IOException e)
	{
		Console.WriteLine(e);
	}	
}
}


Output is -:





Advertisement




  • Example of MemoryStream to write and read a block of bytes at a time.


  • In this example, we are going create an object of the MemoryStream class, which creates an internal array in the memory and then we perform write and read operations with the internal array stored in the memory, by writing/reading a block of bytes from it.

    //C# Example of MemoryStream
    //A program to write bytes to an internal array and to read bytes(a block of bytes) from the same internal array stored in memory
    
    
    using System;
    using System.IO;
    using System.Text;
    
    class A
    {
    public static void Main(String[] ar)
    {
    	try
    	{
    		//Creating a String 
    		String str = "Always look at the bright side of life!";
    
    
    		//Creating a byte array from a String
    		byte[] bA = Encoding.ASCII.GetBytes(str);	
    
    
    		//Creating an object of MemoryStream to write bytes to an internal array
    		//with its capacity 100 bytes.
    		MemoryStream ms = new MemoryStream(100);
    	
    
    		Console.WriteLine("Writing a block of bytes to an internal array");
    
    
    		//Calling the Write(byte[] array, int index, int count) method 
    		//to write all the contents of byte array to the internal array
    		ms.Write(bA, 0, bA.Length);
    
    
    		//Calling the Flush() method to flush all the buffered bytes from the MemoryStream
    		ms.Flush();
    
    
    		//Calling the Seek() method to set the pointer to the beginning of the internal array 
    		ms.Seek(0, SeekOrigin.Begin);
    
    
    		//Total number of bytes in the internal array to read from MemoryStream
    		int num =(int)ms.Length;
    
    
    		//Printing the total number of bytes to read	
    		Console.WriteLine("Number of bytes available to read from internal array: " + num);
    	
    	
    		//Creating a byte array with size equal to the number of bytes to read
    		byte[] b = new byte[num];
    
    		int c;
    	
    		//Read() method stops reading from the internal array when EOF is reached i.e. -1	
    		if( (c = ms.Read(b, 0, b.Length)) != -1) 
    			Console.WriteLine("Number of bytes read from internal array: " + c);
    
    		//Creating a String from the byte array
    		String s = Encoding.UTF8.GetString(b, 0, b.Length);  
    
    		//Printing the contents of internal array
    		Console.WriteLine("The contents read from internal array: " +  s);
    
    		//Closing the byte stream i.e. MemoryStream		
    		ms.Close();
    	}
    	catch(IOException e)
    	{
    		Console.WriteLine(e);
    	}	
    }
    }
    


    Output is -:


    Writing a block of bytes to an internal array
    Number of bytes available to read from internal array: 39
    Number of bytes read from internal array: 39
    The contents read from internal array: Always look at the bright side of life!






    Please share this article -




    < Prev
    Next >
    < C# Directory
    C# Random Access Files >



    Advertisement

    Please Subscribe

    Please subscribe to our social media channels for daily updates.


    Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




    Advertisement



    Notifications



    Please check our latest addition

    C#, PYTHON and DJANGO


    Advertisement