C# MemoryStream Use

Using keyword

You want to see an example of the MemoryStream type in the C# programming language from the System.IO namespace. The MemoryStream is derived from the Stream type and it represents a pure, in-memory stream of data.

This C# article demonstrates the MemoryStream type from System.IO.

Example

Note

First, let's examine this program from a higher level. The program physically reads in the bytes of specified file into the computer's memory; no more disk accesses occur after this. A MemoryStream is constructed from this byte array containing the file's data. Then, the MemoryStream is used as a backing store for the BinaryReader type, which acts upon the in-memory representation.

Program that uses the MemoryStream type [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	// Read all bytes in from a file on the disk.
	byte[] file = File.ReadAllBytes("C:\\ICON1.png");

	// Create a memory stream from those bytes.
	using (MemoryStream memory = new MemoryStream(file))
	{
	    // Use the memory stream in a binary reader.
	    using (BinaryReader reader = new BinaryReader(memory))
	    {
		// Read in each byte from memory.
		for (int i = 0; i < file.Length; i++)
		{
		    byte result = reader.ReadByte();
		    Console.WriteLine(result);
		}
	    }
	}
    }
}

Output
    (The bytes from the file are written.)

137
80
78
71
13
10
26
10
0
0
0
13
73
72...

Usefulness of MemoryStream here. In programming, it sometimes pays to put data into memory and simply leave it there. Memory is much faster than disk or network accesses. With MemoryStream, we can act upon the byte[] array stored in memory rather than a file or other resource. This consolidates resource acquisitions, and also gives you the ability to use multiple streams on a single piece of data reliably.

Memory Hierarchy

Reset MemoryStream

Programming tip

Here's one tip for the MemoryStream type: you can actually reuse a single MemoryStream sometimes. Store the MemoryStream instance as a field; then, call the SetLength(0) method on the MemoryStream instance to reset it. This will reduce allocations during the algorithm.

Summary

Byte type

The MemoryStream type allows you to use in-memory byte arrays or other data as though they are streams. This gives you more flexibility in methods you can use upon these arrays. Instead of storing data in files, you can store data in-memory for additional performance and control over the behavior of your program.

File Handling
.NET