C# Reference ยท Files and I/O
The MemoryStream class
Reference for System.IO.MemoryStream in C#: in-memory read and write, Position, ToArray vs GetBuffer, fixed-size streams, leaveOpen with readers and writers, disposal.
MemoryStream is a Stream whose backing store is a byte array in memory instead of a file or socket. You can write to it, move back to the start, and read what you wrote, all without touching the disk. It is the standard tool for tests, for APIs that demand a stream when you have an array or string, and for building a payload (an image, a compressed block, a serialized object) before sending it somewhere.
A MemoryStream grows automatically when you create it with the default constructor. When you wrap an existing array, the stream has a fixed size and cannot grow beyond it.
using var ms = new MemoryStream(); ms.Write("hello"u8); byte[] bytes = ms.ToArray();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public MemoryStream(); public MemoryStream(int capacity); public MemoryStream(byte[] buffer); public MemoryStream(byte[] buffer, bool writable); public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible);
| Member | Description |
|---|---|
MemoryStream() |
Empty, expandable stream. |
MemoryStream(capacity) |
Expandable, with an initial buffer size (avoids early reallocation). |
MemoryStream(byte[]) |
Wraps the array: fixed size, writable, starts with Length equal to the array length. |
Capacity |
Size of the internal buffer, can be larger than Length. |
ToArray() |
A new array of exactly Length bytes. Works after disposal. |
GetBuffer() |
The internal array (no copy), usually longer than Length. Throws UnauthorizedAccessException for streams that do not expose it, such as new MemoryStream(byte[]). |
TryGetBuffer(out ArraySegment<byte>) |
Safer variant that returns the valid slice. |
WriteTo(Stream) |
Writes the whole content to another stream, regardless of the position. |
Errors: NotSupportedException when you write to a read-only or fixed-size stream beyond its capacity, ObjectDisposedException after Dispose, ArgumentOutOfRangeException for a negative position or a length above int.MaxValue.
Usage notes
- Rewind before reading. The most common bug: you write, then read from the end and get nothing. Set
Position = 0orSeek(0, SeekOrigin.Begin). ToArray()copies;GetBuffer()does not. PreferToArray()for a clean result.GetBuffer()is faster for large data but you must useLength, neverGetBuffer().Length.- Limited to 2 GB (an array limit). For larger data use a file or pooled segments such as
Microsoft.IO.RecyclableMemoryStream(a separate package, not available here). - No real I/O.
Flush()does nothing, and async methods complete synchronously. Disposal does not release much, but still follow theusingconvention because the stream may be passed to code that expects it. CopyToandWriteTodiffer.CopyTocopies from the current position;WriteToalways copies everything.- Wrappers and
leaveOpen.StreamReader,StreamWriter,BinaryReaderandBinaryWriterclose the underlying stream on disposal. PassleaveOpen: truewhen you want to keep using theMemoryStream, andFlushaStreamWriterbefore inspectingLength. - Strings as streams. For tests,
new MemoryStream(Encoding.UTF8.GetBytes(text))turns a string into stream input; remember that this stream has a fixed size. - Growth. The buffer is reallocated and copied as it fills, so pass the expected size to
new MemoryStream(capacity)when you know it.