System.IO.MemoryStream Class

public class MemoryStream : Stream

Base Types

Object
  MarshalByRefObject
    Stream
      MemoryStream

This type implements IDisposable.

Assembly

mscorlib

Library

BCL

Summary

Provides support for creating and using a stream whose backing store is memory.

Description

The MemoryStream class creates streams that have memory as a backing store instead of a disk or a network connection. MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application.

The current position of a stream is the position at which the next read or write operation takes place. The current position can be retrieved or set through the System.IO.MemoryStream.Seek(System.Int64,System.IO.SeekOrigin) method. When a new instance of MemoryStream is created, the current position is set to zero.

The maximum length of a MemoryStream is implementation-specific.

[Note: Memory streams created with an unsigned byte array provide a non-resizable stream view of the data. When using a byte array, you can neither append to nor shrink the stream, although you might be able to modify the existing contents depending on the parameters passed into the constructor.]

See Also

System.IO Namespace

Members

MemoryStream Constructors

MemoryStream(byte[], int, int, bool, bool) Constructor
MemoryStream(byte[], int, int, bool) Constructor
MemoryStream() Constructor
MemoryStream(int) Constructor
MemoryStream(byte[]) Constructor
MemoryStream(byte[], bool) Constructor
MemoryStream(byte[], int, int) Constructor

MemoryStream Methods

MemoryStream.Close Method
MemoryStream.Flush Method
MemoryStream.GetBuffer Method
MemoryStream.Read Method
MemoryStream.ReadByte Method
MemoryStream.Seek Method
MemoryStream.SetLength Method
MemoryStream.ToArray Method
MemoryStream.Write Method
MemoryStream.WriteByte Method
MemoryStream.WriteTo Method

MemoryStream Properties

MemoryStream.CanRead Property
MemoryStream.CanSeek Property
MemoryStream.CanWrite Property
MemoryStream.Capacity Property
MemoryStream.Length Property
MemoryStream.Position Property


MemoryStream(byte[], int, int, bool, bool) Constructor

public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible);

Summary

Constructs and initializes a new instance of the MemoryStream class.

Parameters

buffer
The Byte array from which to create the new stream.
index
A Int32 that specifies the index into buffer at which the stream begins.
count
A Int32 that specifies the length of the stream in bytes.
writable
A Boolean that specifies whether the new stream instance supports writing.
publiclyVisible
A Boolean that specifies whether buffer is exposed via System.IO.MemoryStream.GetBuffer, which returns the Byte array from which the stream was created. Specify true to expose buffer; otherwise, specify false .

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
ArgumentOutOfRangeExceptionindex or count is negative.
ArgumentException(index + count ) is greater than the length of buffer.

Description

The System.IO.MemoryStream.CanRead and System.IO.MemoryStream.CanSeek properties of the new MemoryStream instance are set to true . The System.IO.MemoryStream.Capacity property is set to count. The System.IO.Stream.CanWrite property is set to writable.

[Note: The new stream instance can be written to depending on the value of writable, but the System.IO.MemoryStream.Capacity of the underlying Byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength(System.Int64)).]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream(byte[], int, int, bool) Constructor

public MemoryStream(byte[] buffer, int index, int count, bool writable);

Summary

Constructs and initializes a new non-resizable instance of the MemoryStream class.

Parameters

buffer
The Byte array from which to create the new stream.
index
A Int32 that specifies the index in buffer at which the stream begins.
count
A Int32 that specifies the length of the stream in bytes.
writable
A Boolean that specifies whether the new stream instance supports writing.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
ArgumentOutOfRangeExceptionindex or count are negative.
ArgumentException(index + count ) is greater than the length of buffer.

Description

The System.IO.MemoryStream.CanRead and System.IO.MemoryStream.CanSeek properties of the new MemoryStream are set to true . The System.IO.MemoryStream.Capacity property is set to count. The System.IO.Stream.CanWrite property is set to writable.

[Note: The new stream instance can be written to depending on the value of writable, but the System.IO.MemoryStream.Capacity of the underlying byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength(System.Int64)).]

The new stream does not expose the underlying byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw UnauthorizedAccessException.

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream() Constructor

public MemoryStream();

Summary

Constructs and initializes a new resizable instance of the MemoryStream class.

Description

The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new instance of the MemoryStream class are set to true .

The capacity of the new stream instance can be increased by using the System.IO.MemoryStream.SetLength(System.Int64) method or by setting the System.IO.MemoryStream.Capacity property.

The new stream exposes the underlying byte buffer, which can be accessed through the System.IO.MemoryStream.GetBuffer method.

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream(int) Constructor

public MemoryStream(int capacity);

Summary

Constructs and initializes a new resizable instance of the MemoryStream class.

Parameters

capacity
A Int32 that specifies the initial size of the internal Byte array.

Exceptions

Exception TypeCondition
ArgumentOutOfRangeExceptioncapacity is negative.

Description

The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new instance of the MemoryStream class are set to true .

The System.IO.MemoryStream.Capacity of the new stream instance is set to capacity can be increased by using the System.IO.MemoryStream.SetLength(System.Int64) method or by setting the System.IO.MemoryStream.Capacity property. Write operations at the end of the new instance of the MemoryStream class expand the MemoryStream.

The new stream exposes the underlying byte buffer, which can be accessed through the System.IO.MemoryStream.GetBuffer method.

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream(byte[]) Constructor

public MemoryStream(byte[] buffer);

Summary

Constructs and initializes a new non-resizable instance of the MemoryStream class.

Parameters

buffer
The Byte array from which to create the new stream.

Exceptions

Exception TypeCondition
ArgumentNullExceptionThe buffer parameter is null .

Description

The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new instance of the MemoryStream class are set to true . System.IO.MemoryStream.Capacity is set to the length of the specified Byte array.

[Note: The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying Byte array cannot be changed. The length of the stream cannot be set to a value greater than System.IO.MemoryStream.Capacity , but the stream can be truncated (see System.IO.MemoryStream.SetLength(System.Int64)).]

The new stream does not expose the underlying byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw UnauthorizedAccessException.

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream(byte[], bool) Constructor

public MemoryStream(byte[] buffer, bool writable);

Summary

Constructs and initializes a new non-resizable instance of the MemoryStream class.

Parameters

buffer
The Byte array from which to create the new stream.
writable
A Boolean that specifies whether the new stream instance supports writing.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .

Description

The System.IO.Stream.CanRead and System.IO.Stream.CanSeek properties of the new instance of the MemoryStream class are set to true . The System.IO.MemoryStream.Capacity property is set to the length of the specified Byte array. The System.IO.Stream.CanWrite property is set to writable .

[Note: The new stream instance can be written to depending on the value of writable, but the System.IO.MemoryStream.Capacity of the underlying Byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength(System.Int64)).]

The new stream does not expose the underlying Byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw UnauthorizedAccessException.

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream(byte[], int, int) Constructor

public MemoryStream(byte[] buffer, int index, int count);

Summary

Constructs and initializes a new non-resizable instance of the MemoryStream class.

Parameters

buffer
The Byte array from which to create the new stream.
index
A Int32 that specifies the index into buffer at which the stream begins.
count
A Int32 that specifies the length of the stream in bytes.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
ArgumentOutOfRangeExceptionindex or count is less than zero.
ArgumentException(index + count ) is greater than the length of buffer.

Description

The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new MemoryStream instance are set to true . The System.IO.MemoryStream.Capacity property is set to count .

[Note: The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying Byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength(System.Int64)).]

The new stream does not expose the underlying Byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw UnauthorizedAccessException .

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.Close Method

public override void Close();

Summary

Closes the current MemoryStream instance.

Description

The stream will not support reading or writing after this method is invoked. Following a call to System.IO.MemoryStream.Close , operations on the stream can raise an exception.

The buffer of a closed MemoryStream is still available, and the System.IO.MemoryStream.ToArray and System.IO.MemoryStream.GetBuffer methods can be called successfully.

[Note: This method overrides System.IO.Stream.Close .]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.Flush Method

public override void Flush();

Summary

Overrides System.IO.Stream.Flush so that no action is performed.

Description

Since any data written to a MemoryStream is written into RAM, this method is redundant.

[Note: This method overrides System.IO.Stream.Flush.]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.GetBuffer Method

public virtual byte[] GetBuffer();

Summary

Returns the array of unsigned bytes from which this stream was created.

Return Value

The Byte array from which the current stream was created, or the underlying array if a Byte array was not provided to the MemoryStream constructor during construction of the current instance.

Exceptions

Exception TypeCondition
UnauthorizedAccessExceptionThe current instance was not created with a publicly visible buffer.

Description

To create a MemoryStream instance with a publicly visible buffer use the default constructor, MemoryStream( Byte [], Int32, Int32, Boolean, true ) or MemoryStream(Int32 ) constructor.

If the current stream is resizable, multiple calls to this method do not return the same array if the underlying Byte array is resized between calls. For additional information, see System.IO.MemoryStream.Capacity .

[Note: This method works when the MemoryStream is closed.]

[Behaviors: As described above.]

Example

The following example demonstrates that two calls to the System.IO.MemoryStream.GetBuffer method on a resizable stream do not return the same array if the underlying byte array is reallocated.

using System;
using System.IO;

public class MemoryStreamTest {
   public static void Main() {

      MemoryStream ms = new MemoryStream(10);

      byte[] a = ms.GetBuffer();
      byte[] b = ms.GetBuffer();

      //Force reallocation of the underlying byte array.
      ms.Capacity = 10240;    
      byte[] c = ms.GetBuffer();


      if(Object.ReferenceEquals(a, b))
         Console.WriteLine("a and b represent the same instance.");
      else
         Console.WriteLine("a and b represent the different instances.");

      if(Object.ReferenceEquals(a, c))
         Console.WriteLine("a and c represent the same instance.");
      else
         Console.WriteLine("a and c represent the different instances.");

   }
}
The output is

a and b represent the same instance.

a and c represent the different instances.

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.Read Method

public override int Read(byte[] buffer, int offset, int count);

Summary

Reads a block of bytes from the current stream at the current position, and writes the data to the specified byte array.

Parameters

buffer
A Byte array. When this method returns, buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the characters read from the current stream.
offset
A Int32 that specifies the byte offset in buffer at which to begin writing.
count
A Int32 that specifies the maximum number of bytes to read.

Return Value

A Int32 that specifies the total number of bytes written into the buffer, or zero if the end of the stream is reached before any bytes are read.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
ArgumentOutOfRangeExceptionoffset or count is negative.
ArgumentException(offset + count ) is larger than the length of buffer.
ObjectDisposedException The current stream is closed.

Description

If the read operation is successful, the current position within the stream advances by the number of bytes read. If an exception occurs, the current position within the stream remains unchanged.

If the read takes place immediately following a seek beyond the end of the stream, the end of the stream is reached.

[Note: If the byte array specified in the buffer parameter is the underlying buffer returned by the System.IO.MemoryStream.GetBuffer method, the array contents are overwritten, and no exception is thrown.

This method overrides System.IO.Stream.Read(System.Byte[],System.Int32,System.Int32).

]

Example

The following example demonstrates the result of reading from a MemoryStream into its underlying byte array.

using System;
using System.IO;

public class MemoryStreamTest {
   public static void Main() {

      byte[] values = new byte [] {0,1,2,3,4,5,6,7,8,9};

      foreach (byte b in values) {
         Console.Write(b);
      }

      Console.WriteLine();

      MemoryStream ms = new MemoryStream (values);

      ms.Read(values, 1, 5);

      foreach (byte b in values) {
         Console.Write(b);
      }
   }
}
The output is

0123456789

0012346789

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.ReadByte Method

public override int ReadByte();

Summary

Reads a byte from the current stream at the current position.

Return Value

The byte cast to a Int32, or -1 if the end of the stream has been reached.

Exceptions

Exception TypeCondition
ObjectDisposedException The current stream is closed.

Description

If the read operation is successful, the current position within the stream is advanced by one byte. If an exception occurs, the current position within the stream is unchanged.

If the read takes place immediately following a seek beyond the end of the stream, the end of the stream is reached.

[Note: This method overrides System.IO.Stream.ReadByte.]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.Seek Method

public override long Seek(long offset, SeekOrigin loc);

Summary

Changes the position within the current stream by the given offset, which is relative to the stated origin.

Parameters

offset
A Int64 that specifies the new position within the stream. This is relative to the loc parameter, and can be positive or negative.
loc
A SeekOrigin value that specifies the seek reference point.

Return Value

A Int64 containing the new position within the stream, calculated by combining the seek reference point and the offset.

Exceptions

Exception TypeCondition
IOExceptionSeeking is attempted before the beginning of the stream.
ArgumentOutOfRangeExceptionoffset is greater than the maximum length of MemoryStream.
ArgumentExceptionloc is not a valid SeekOrigin value.
ObjectDisposedException The current stream is closed.

Description

[Note: This method overrides System.IO.Stream.Seek(System.Int64,System.IO.SeekOrigin).]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.SetLength Method

public override void SetLength(long value);

Summary

Sets the length of the current stream to the specified value.

Parameters

value
A Int64 that specifies the value at which to set the length.

Exceptions

Exception TypeCondition
NotSupportedExceptionThe current stream is not resizable and value is greater than the current System.IO.MemoryStream.Capacity.

-or-

The current stream does not support writing.

ArgumentOutOfRangeExceptionvalue is negative or is greater than the maximum length of the MemoryStream - origin, where origin is the index into the underlying buffer at which the stream starts.

Description

If the specified value is less than the current length of the stream, the stream is truncated. If after the truncation the current position within the stream is past the end of the stream, the System.IO.MemoryStream.ReadByte method returns -1, the System.IO.MemoryStream.Read(System.Byte[],System.Int32,System.Int32) method reads zero bytes into the provided byte array, and System.IO.MemoryStream.Write(System.Byte[],System.Int32,System.Int32) and System.IO.MemoryStream.WriteByte(System.Byte) methods append specified bytes at the end of the stream, increasing its length.

If the specified value is larger than the current capacity and the stream is resizable, the capacity is increased, and the current position within the stream is unchanged. If the length is increased, the contents of the stream between the old and the new length are initialized to zeros.

[Note: A MemoryStream instance must support writing for this method to work. Use the System.IO.MemoryStream.CanWrite property to determine whether the current instance supports writing. For additional information, see System.IO.Stream.CanWrite .

This method overrides System.IO.Stream.SetLength(System.Int64).

]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.ToArray Method

public virtual byte[] ToArray();

Summary

Writes the entire stream contents to a Byte array, regardless of the current position within the stream.

Return Value

A new Byte array.

Description

This method returns a copy of the contents of the MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which the current instance has access is returned. [Note: For additional information, see the MemoryStream (Byte[], Int32, Int32 ) constructor.]

[Note: This method works when the MemoryStream is closed.]

[Behaviors: As described above.]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.Write Method

public override void Write(byte[] buffer, int offset, int count);

Summary

Writes a block of bytes to the current stream at the current position using data read from buffer.

Parameters

buffer
The Byte array to write data from.
offset
A Int32 that specifies the zero based byte offset into buffer at which to begin writing from.
count
A Int32 that specifies the maximum number of bytes to write from buffer.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
NotSupportedExceptionThe current stream does not support writing.

-or-

The current position is closer than count bytes to the end of the stream, and the capacity cannot be modified.

ArgumentException(offset + count ) is greater than the length of buffer.
ArgumentOutOfRangeExceptionoffset or count are negative.
IOExceptionAn I/O error occurred.
ObjectDisposedExceptionThe current stream is closed.

Description

If the write operation is successful, the current position within the stream is advanced by the number of bytes written. If an exception occurs, the current position within the stream is unchanged.

If the write takes place immediately following a seek beyond the end of the stream, that stream is zero-byte-extended to the new seek position before the given bytes are written.

Write operations at the end of a resizable MemoryStream expand the MemoryStream.

[Note: Use the System.IO.MemoryStream.CanWrite method to determine whether the current stream supports writing.]

[Note: This method overrides System.IO.Stream.Write(System.Byte[],System.Int32,System.Int32).]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.WriteByte Method

public override void WriteByte(byte value);

Summary

Writes a Byte to the current stream at the current position.

Parameters

value
The Byte to write.

Exceptions

Exception TypeCondition
ObjectDisposedExceptionThe current stream is closed.
NotSupportedExceptionThe current stream does not support writing.

-or-

The current position is at the end of the stream, and the stream's capacity cannot be modified.

Description

Write operations at the end of a resizable MemoryStream expand the MemoryStream. If the write operation is successful, the current position within the stream is advanced by one byte. If an exception occurs, the position is unchanged.

If the write takes place immediately following a seek beyond the end of the stream, that stream is zero-byte-extended to the new seek position before the given byte is written.

[Note: Use the System.IO.MemoryStream.CanWrite method to determine whether the current stream supports writing.]

[Note: This method overrides System.IO.Stream.WriteByte(System.Byte).]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.WriteTo Method

public virtual void WriteTo(Stream stream);

Summary

Writes the entire contents of the current MemoryStream instance to a specified stream.

Parameters

stream
The Stream to write the current memory stream to.

Exceptions

Exception TypeCondition
ArgumentNullExceptionstream is null .
ObjectDisposedExceptionThe current or target stream is closed.

Description

[Note: This method is equivalent to calling stream.Write(this.GetBuffer(), 0, this.GetBuffer().Length) and passing in the underlying buffer of the current instance.]

[Behaviors: As described above.]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.CanRead Property

public override bool CanRead { get; }

Summary

Gets a Boolean value indicating whether the current stream supports reading.

Property Value

true if the current stream is open and supports reading; otherwise false .

Description

This property is read-only.

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.CanSeek Property

public override bool CanSeek { get; }

Summary

Gets a Boolean value indicating whether the current stream supports seeking.

Property Value

true if the stream is open and supports seeking; otherwise false .

Description

This property is read-only.

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.CanWrite Property

public override bool CanWrite { get; }

Summary

Gets a Boolean value indicating whether the current stream supports writing.

Property Value

true if the stream supports writing; otherwise, false .

Description

This property is read-only.

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.Capacity Property

public virtual int Capacity { get; set; }

Summary

Gets or sets the number of bytes allocated for the current stream.

Property Value

A Int32 containing the number of bytes allocated for the current stream.

Exceptions

Exception TypeCondition
ArgumentOutOfRangeExceptionThe value specified for a set operation is negative or less than the current length of the stream.
NotSupportedExceptionA set operation was attempted on a stream whose capacity cannot be modified.
ObjectDisposedExceptionThe current stream is closed.

Description

System.IO.MemoryStream.Capacity is the buffer length for system-provided byte arrays. If the current stream is created with a specified Byte array, System.IO.MemoryStream.Capacity indicates the length of the portion of the provided array to which the current stream has access. [Note: For additional information, see the MemoryStream (Byte[], Int32, Int32 ) constructor. ]

System.IO.MemoryStream.Capacity cannot be set to a value less than the current length of the stream, but can be set to less than the current capacity. If the capacity specified is less than the current capacity, the size of the buffer used to hold the stream can be reduced, but need not be.

[Note: If the value specified for a set operation is less than the default value, for performance reasons the property is set to the default. The default value of the System.IO.MemoryStream.Capacity property is unspecified. ]

[Behaviors: As described above.]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.Length Property

public override long Length { get; }

Summary

Gets the length of the stream in bytes.

Property Value

A Int64 containing the length of the stream in bytes.

Exceptions

Exception TypeCondition
ObjectDisposedExceptionThe current stream is closed.

Description

This property is read-only.

[Note: This property overrides System.IO.Stream.Length.]

See Also

System.IO.MemoryStream Class, System.IO Namespace

MemoryStream.Position Property

public override long Position { get; set; }

Summary

Gets or sets the current position within the stream.

Property Value

A Int64 containing the current position within the stream.

Exceptions

Exception TypeCondition
ArgumentOutOfRangeExceptionThe value specified for a set operation is negative or greater than the maximum length of a MemoryStream.
ObjectDisposedExceptionThe current stream is closed.

Description

[Note: This property overrides System.IO.Stream.Position.]

See Also

System.IO.MemoryStream Class, System.IO Namespace