ZetCode

C# MemoryStream

last modified November 6, 2026

In this article we show how to use the MemoryStream class in C#.

MemoryStream from the System.IO namespace is a stream whose data is stored in a byte array in memory instead of a file or a network connection. It supports reading, writing, and seeking like a FileStream. It is used to build binary data before sending or saving it, to pass data to APIs that accept a Stream, and to test code that normally writes to files.

A MemoryStream holds no operating system resources, so disposing it is not strictly necessary, but a using statement keeps the code consistent with other streams.

Writing and reading bytes

The first example writes bytes to a memory stream and reads them back.

Program.cs
using System.Text;

using var ms = new MemoryStream();

byte[] data = Encoding.UTF8.GetBytes("an old falcon");
ms.Write(data);

Console.WriteLine($"Length: {ms.Length}, Position: {ms.Position}");

ms.Position = 0;

byte[] buffer = new byte[ms.Length];
ms.ReadExactly(buffer);

Console.WriteLine(Encoding.UTF8.GetString(buffer));
Console.WriteLine($"Length: {ms.Length}, Position: {ms.Position}");

We write the UTF-8 bytes of a string and print the length and position of the stream.

ms.Position = 0;

Writing moves the position to the end of the data. Before reading, we must move it back to the start; otherwise the read finds no data.

ms.ReadExactly(buffer);

ReadExactly fills the buffer with the whole content. Reading does not remove data from the stream; only the position changes.

$ dotnet run
Length: 13, Position: 13
an old falcon
Length: 13, Position: 13

Text in memory

A StreamWriter and StreamReader work with a memory stream the same way as with a file.

Program.cs
using var ms = new MemoryStream();

using (var writer = new StreamWriter(ms, leaveOpen: true))
{
    writer.WriteLine("sky");
    writer.WriteLine("cloud");
    writer.WriteLine("rain");
}

Console.WriteLine($"{ms.Length} bytes written");

ms.Position = 0;

using var reader = new StreamReader(ms);
string? line;

while ((line = reader.ReadLine()) != null)
{
    Console.WriteLine(line.ToUpperInvariant());
}

We write three lines and read them back in upper case.

using (var writer = new StreamWriter(ms, leaveOpen: true))

Disposing a writer normally closes the stream under it. With leaveOpen, the memory stream stays usable after the writer is disposed. Disposing the writer also flushes its buffer, so all three lines are in the stream: 15 bytes including the newlines.

$ dotnet run
15 bytes written
SKY
CLOUD
RAIN

Capacity

A memory stream created without data grows as we write. The Capacity property is the size of the internal array and Length is the amount of data in it.

Program.cs
using var ms = new MemoryStream();
Console.WriteLine($"initial capacity: {ms.Capacity}");

int last = ms.Capacity;
byte[] chunk = new byte[100];

for (int i = 0; i < 50; i++)
{
    ms.Write(chunk);

    if (ms.Capacity != last)
    {
        Console.WriteLine($"length {ms.Length,5} -> capacity {ms.Capacity}");
        last = ms.Capacity;
    }
}

using var sized = new MemoryStream(capacity: 5000);
sized.Write(new byte[5000]);
Console.WriteLine($"preallocated: length {sized.Length}, capacity {sized.Capacity}");

We write 100 bytes at a time and print the capacity whenever it changes.

if (ms.Capacity != last)

The capacity starts at 0, jumps to 256 at the first write, and then doubles when more space is needed. Each growth allocates a new array and copies the data.

using var sized = new MemoryStream(capacity: 5000);

When the final size is known, passing it to the constructor avoids the copying.

$ dotnet run
initial capacity: 0
length   100 -> capacity 256
length   300 -> capacity 512
length   600 -> capacity 1024
length  1100 -> capacity 2048
length  2100 -> capacity 4096
length  4100 -> capacity 8192
preallocated: length 5000, capacity 5000

ToArray, GetBuffer, and TryGetBuffer

There are three ways to get the bytes out of a memory stream.

Program.cs
using var ms = new MemoryStream();
ms.Write([1, 2, 3, 4, 5]);

byte[] copy = ms.ToArray();
Console.WriteLine($"ToArray: {copy.Length} bytes");

byte[] raw = ms.GetBuffer();
Console.WriteLine($"GetBuffer: {raw.Length} bytes, length {ms.Length}");

if (ms.TryGetBuffer(out ArraySegment<byte> segment))
{
    Console.WriteLine($"TryGetBuffer: {segment.Count} bytes: {string.Join(" ", segment)}");
}

raw[0] = 99;
copy[1] = 77;
Console.WriteLine($"stream content: {string.Join(" ", ms.ToArray())}");

We write five bytes and access them with each method.

byte[] copy = ms.ToArray();

ToArray returns a new array with exactly the data of the stream. It is the safest choice, but it copies the data.

byte[] raw = ms.GetBuffer();

GetBuffer returns the internal array without copying. It includes the unused capacity, so its length is 256, and only the first Length bytes are valid.

if (ms.TryGetBuffer(out ArraySegment<byte> segment))

TryGetBuffer also avoids the copy and returns a segment limited to the valid data.

raw[0] = 99;
copy[1] = 77;

Changing the internal array changes the stream, while changing the copy does not.

$ dotnet run
ToArray: 5 bytes
GetBuffer: 256 bytes, length 5
TryGetBuffer: 5 bytes: 1 2 3 4 5
stream content: 99 2 3 4 5

Streams over existing arrays

A memory stream can be created over an existing byte array. Such a stream reads and writes the array directly and cannot grow.

Program.cs
byte[] data = [10, 20, 30, 40];

using (var ms = new MemoryStream(data))
{
    ms.Position = 1;
    ms.WriteByte(99);
    Console.WriteLine($"array after write: {string.Join(" ", data)}");

    try
    {
        ms.Position = 4;
        ms.WriteByte(50);
    }
    catch (NotSupportedException e)
    {
        Console.WriteLine($"NotSupportedException: {e.Message}");
    }

    try
    {
        ms.GetBuffer();
    }
    catch (UnauthorizedAccessException e)
    {
        Console.WriteLine($"UnauthorizedAccessException: {e.Message}");
    }
}

using (var readOnly = new MemoryStream(data, writable: false))
{
    Console.WriteLine($"CanWrite: {readOnly.CanWrite}, first byte: {readOnly.ReadByte()}");
}

using (var slice = new MemoryStream(data, index: 2, count: 2))
{
    Console.WriteLine($"slice length: {slice.Length}, first byte: {slice.ReadByte()}");
}

We create several streams over the same array.

ms.Position = 1;
ms.WriteByte(99);

Writing changes the original array.

ms.Position = 4;
ms.WriteByte(50);

Writing past the end of the array throws NotSupportedException, because the stream is not expandable.

ms.GetBuffer();

GetBuffer is not allowed for streams created over an array, unless the constructor with the publiclyVisible parameter is used. ToArray and TryGetBuffer work in all cases; TryGetBuffer returns false when the buffer is not visible.

using (var readOnly = new MemoryStream(data, writable: false))

With writable set to false, the stream is read-only.

using (var slice = new MemoryStream(data, index: 2, count: 2))

The index and count parameters create a stream over a part of the array.

$ dotnet run
array after write: 10 99 30 40
NotSupportedException: Memory stream is not expandable.
UnauthorizedAccessException: MemoryStream's internal buffer cannot be accessed.
CanWrite: False, first byte: 10
slice length: 2, first byte: 30

Testing code that writes to a stream

A method that writes to a Stream instead of a file path can be tested with a memory stream, without touching the disk.

Program.cs
using System.Text;

record Product(string Name, decimal Price);

static class Program
{
    static void Main()
    {
        Product[] products = [new("pen", 1.20m), new("notebook", 3.50m), new("eraser", 0.80m)];

        using var ms = new MemoryStream();
        WriteCsv(ms, products);

        string csv = Encoding.UTF8.GetString(ms.ToArray());
        Console.Write(csv);

        bool ok = csv.Split('\n', StringSplitOptions.RemoveEmptyEntries).Length == products.Length + 1;
        Console.WriteLine($"test passed: {ok}");
    }

    static void WriteCsv(Stream output, IEnumerable<Product> products)
    {
        using var writer = new StreamWriter(output, leaveOpen: true) { NewLine = "\n" };
        writer.WriteLine("name,price");

        foreach (var p in products)
        {
            writer.WriteLine(FormattableString.Invariant($"{p.Name},{p.Price}"));
        }
    }
}

The WriteCsv method writes products as CSV. We call it with a memory stream and check the result.

static void WriteCsv(Stream output, IEnumerable<Product> products)

The method accepts any stream. In production it gets a FileStream or a network stream; in a test, a MemoryStream.

writer.WriteLine(FormattableString.Invariant($"{p.Name},{p.Price}"));

FormattableString.Invariant formats the price with a dot, whatever the culture of the machine, which keeps the CSV and the test output stable.

string csv = Encoding.UTF8.GetString(ms.ToArray());

The test converts the bytes to a string and checks that there is a header and one line per product.

$ dotnet run
name,price
pen,1.20
notebook,3.50
eraser,0.80
test passed: True

Compressing data in memory

Memory streams are often combined with other streams, for example with a compression stream.

Program.cs
using System.IO.Compression;
using System.Text;

string text = string.Concat(Enumerable.Repeat("the quick brown fox jumps over the lazy dog\n", 100));
byte[] original = Encoding.UTF8.GetBytes(text);

using var compressed = new MemoryStream();

using (var gzip = new GZipStream(compressed, CompressionLevel.Optimal, leaveOpen: true))
{
    gzip.Write(original);
}

Console.WriteLine($"original: {original.Length} bytes, compressed: {compressed.Length} bytes");

compressed.Position = 0;

using var restored = new MemoryStream();

using (var gunzip = new GZipStream(compressed, CompressionMode.Decompress))
{
    gunzip.CopyTo(restored);
}

Console.WriteLine($"restored: {restored.Length} bytes, equal: {restored.ToArray().AsSpan().SequenceEqual(original)}");

We compress a repetitive text with gzip into a memory stream and decompress it into another one.

using (var gzip = new GZipStream(compressed, CompressionLevel.Optimal, leaveOpen: true))

The GZipStream writes compressed data into the memory stream. The compressed data is complete only after the gzip stream is disposed, so we dispose it before reading the length, and keep the memory stream open.

gunzip.CopyTo(restored);

For decompression, we read from the gzip stream and copy the result into a second memory stream. The restored bytes equal the original.

$ dotnet run
original: 4400 bytes, compressed: 110 bytes
restored: 4400 bytes, equal: True

Saving a stream to a file

Content built in memory can be saved to another stream with the WriteTo method.

Program.cs
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "report.txt");

using var ms = new MemoryStream();

using (var writer = new StreamWriter(ms, leaveOpen: true))
{
    for (int i = 1; i <= 3; i++)
    {
        writer.WriteLine($"section {i}");
    }
}

using (var file = new FileStream(path, FileMode.Create, FileAccess.Write))
{
    ms.WriteTo(file);
}

Console.Write(File.ReadAllText(path));
Console.WriteLine($"position after WriteTo: {ms.Position}");

Directory.Delete("demo", true);

We write a small report into memory and save it to a file.

ms.WriteTo(file);

WriteTo writes the whole content of the memory stream, whatever its current position, and does not change the position. CopyTo, by contrast, copies from the current position, which would be the end here.

$ dotnet run
section 1
section 2
section 3
position after WriteTo: 30

Source

MemoryStream class

In this article we have worked with the MemoryStream class in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.