MemoryStream. This C# class represents a pure, in-memory stream of data. It is found in the System.IO namespace. It is derived from the Stream type.
Type uses. MemoryStream is useful when using BinaryReader and other classes that can receive streams. It can be reset—this leads to performance improvements.
Example code. First, this C# program physically reads in the bytes of specified file into the computer's memory. No more disk accesses occur after this.
Info 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.
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);
}
}
}
}
}137
80
78
71
13
10
26
10
0
0
0
13
73
72...
A discussion. Memory is much faster than disk or network accesses. With the MemoryStream class, we can act upon the byte array stored in memory rather than a file or other resource.
Note This consolidates resource acquisitions. It also gives you the ability to reliably use multiple streams on a single piece of data.
Also You can sometimes reuse a single Memory Stream. Store the MemoryStream instance as a field.
Then Call the Set Length (0) method on the Memory Stream instance to reset it. This will reduce allocations during the algorithm.
A summary. MemoryStream in C# programs allows you to use in-memory byte arrays or other data as though they are streams. Instead of storing data in files, you can store data in-memory.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jul 31, 2021 (image).