MemoryStream Class

Definition

Creates a stream whose backing store is memory.

public ref class MemoryStream : System::IO::Stream
public class MemoryStream : System.IO.Stream
[System.Serializable]
public class MemoryStream : System.IO.Stream
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class MemoryStream : System.IO.Stream
type MemoryStream = class
    inherit Stream
[<System.Serializable>]
type MemoryStream = class
    inherit Stream
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type MemoryStream = class
    inherit Stream
Public Class MemoryStream
Inherits Stream
Inheritance
MemoryStream
Inheritance
Attributes

Examples

The following code example shows how to read and write data using memory as a backing store.

using namespace System;
using namespace System::IO;
using namespace System::Text;

int main()
{
   int count;
   array<Byte>^byteArray;
   array<Char>^charArray;
   UnicodeEncoding^ uniEncoding = gcnew UnicodeEncoding;

   // Create the data to write to the stream.
   array<Byte>^firstString = uniEncoding->GetBytes( "Invalid file path characters are: " );
   array<Byte>^secondString = uniEncoding->GetBytes( Path::InvalidPathChars );

   MemoryStream^ memStream = gcnew MemoryStream( 100 );
   try
   {
      // Write the first string to the stream.
      memStream->Write( firstString, 0, firstString->Length );

      // Write the second string to the stream, byte by byte.
      count = 0;
      while ( count < secondString->Length )
      {
         memStream->WriteByte( secondString[ count++ ] );
      }

      
      // Write the stream properties to the console.
      Console::WriteLine( "Capacity = {0}, Length = {1}, "
      "Position = {2}\n", memStream->Capacity.ToString(), memStream->Length.ToString(), memStream->Position.ToString() );

      // Set the stream position to the beginning of the stream.
      memStream->Seek( 0, SeekOrigin::Begin );

      // Read the first 20 bytes from the stream.
      byteArray = gcnew array<Byte>(memStream->Length);
      count = memStream->Read( byteArray, 0, 20 );

      // Read the remaining bytes, byte by byte.
      while ( count < memStream->Length )
      {
         byteArray[ count++ ] = Convert::ToByte( memStream->ReadByte() );
      }
      
      // Decode the Byte array into a Char array 
      // and write it to the console.
      charArray = gcnew array<Char>(uniEncoding->GetCharCount( byteArray, 0, count ));
      uniEncoding->GetDecoder()->GetChars( byteArray, 0, count, charArray, 0 );
      Console::WriteLine( charArray );
   }
   finally
   {
      memStream->Close();
   }
}
using System;
using System.IO;
using System.Text;

class MemStream
{
    static void Main()
    {
        int count;
        byte[] byteArray;
        char[] charArray;
        UnicodeEncoding uniEncoding = new UnicodeEncoding();

        // Create the data to write to the stream.
        byte[] firstString = uniEncoding.GetBytes(
            "Invalid file path characters are: ");
        byte[] secondString = uniEncoding.GetBytes(
            Path.GetInvalidPathChars());

        using(MemoryStream memStream = new MemoryStream(100))
        {
            // Write the first string to the stream.
            memStream.Write(firstString, 0 , firstString.Length);

            // Write the second string to the stream, byte by byte.
            count = 0;
            while(count < secondString.Length)
            {
                memStream.WriteByte(secondString[count++]);
            }

            // Write the stream properties to the console.
            Console.WriteLine(
                "Capacity = {0}, Length = {1}, Position = {2}\n",
                memStream.Capacity.ToString(),
                memStream.Length.ToString(),
                memStream.Position.ToString());

            // Set the position to the beginning of the stream.
            memStream.Seek(0, SeekOrigin.Begin);

            // Read the first 20 bytes from the stream.
            byteArray = new byte[memStream.Length];
            count = memStream.Read(byteArray, 0, 20);

            // Read the remaining bytes, byte by byte.
            while(count < memStream.Length)
            {
                byteArray[count++] = (byte)memStream.ReadByte();
            }

            // Decode the byte array into a char array
            // and write it to the console.
            charArray = new char[uniEncoding.GetCharCount(
                byteArray, 0, count)];
            uniEncoding.GetDecoder().GetChars(
                byteArray, 0, count, charArray, 0);
            Console.WriteLine(charArray);
        }
    }
}
Imports System.IO
Imports System.Text

Module MemStream

    Sub Main()
    
        Dim count As Integer
        Dim byteArray As Byte()
        Dim charArray As Char()
        Dim uniEncoding As New UnicodeEncoding()

        ' Create the data to write to the stream.
        Dim firstString As Byte() = _
            uniEncoding.GetBytes("Invalid file path characters are: ")
        Dim secondString As Byte() = _
            uniEncoding.GetBytes(Path.GetInvalidPathChars())

        Dim memStream As New MemoryStream(100)
        Try
            ' Write the first string to the stream.
            memStream.Write(firstString, 0 , firstString.Length)

            ' Write the second string to the stream, byte by byte.
            count = 0
            While(count < secondString.Length)
                memStream.WriteByte(secondString(count))
                count += 1
            End While
            
            ' Write the stream properties to the console.
            Console.WriteLine( _
                "Capacity = {0}, Length = {1}, Position = {2}", _
                memStream.Capacity.ToString(), _
                memStream.Length.ToString(), _
                memStream.Position.ToString())

            ' Set the stream position to the beginning of the stream.
            memStream.Seek(0, SeekOrigin.Begin)

            ' Read the first 20 bytes from the stream.
            byteArray = _
                New Byte(CType(memStream.Length, Integer)){}
            count = memStream.Read(byteArray, 0, 20)

            ' Read the remaining Bytes, Byte by Byte.
            While(count < memStream.Length)
                byteArray(count) = _
                    Convert.ToByte(memStream.ReadByte())
                count += 1
            End While

            ' Decode the Byte array into a Char array 
            ' and write it to the console.
            charArray = _
                New Char(uniEncoding.GetCharCount( _
                byteArray, 0, count)){}
            uniEncoding.GetDecoder().GetChars( _
                byteArray, 0, count, charArray, 0)
            Console.WriteLine(charArray)
        Finally
            memStream.Close()
        End Try

    End Sub
End Module

Remarks

The current position of a stream is the position at which the next read or write operation could take place. The current position can be retrieved or set through the Seek method. When a new instance of MemoryStream is created, the current position is set to zero.

Note

This type implements the IDisposable interface, but does not actually have any resources to dispose. This means that disposing it by directly calling Dispose() or by using a language construct such as using (in C#) or Using (in Visual Basic) is not necessary.

Memory streams created with an unsigned byte array provide a non-resizable stream 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. Empty memory streams are resizable, and can be written to and read from.

If a MemoryStream object is added to a ResX file or a .resources file, call the GetStream method at runtime to retrieve it.

If a MemoryStream object is serialized to a resource file it will actually be serialized as an UnmanagedMemoryStream. This behavior provides better performance, as well as the ability to get a pointer to the data directly, without having to go through Stream methods.

Constructors

MemoryStream()

Initializes a new instance of the MemoryStream class with an expandable capacity initialized to zero.

MemoryStream(Byte[])

Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array.

MemoryStream(Byte[], Boolean)

Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array with the CanWrite property set as specified.

MemoryStream(Byte[], Int32, Int32)

Initializes a new non-resizable instance of the MemoryStream class based on the specified region (index) of a byte array.

MemoryStream(Byte[], Int32, Int32, Boolean)

Initializes a new non-resizable instance of the MemoryStream class based on the specified region of a byte array, with the CanWrite property set as specified.

MemoryStream(Byte[], Int32, Int32, Boolean, Boolean)

Initializes a new instance of the MemoryStream class based on the specified region of a byte array, with the CanWrite property set as specified, and the ability to call GetBuffer() set as specified.

MemoryStream(Int32)

Initializes a new instance of the MemoryStream class with an expandable capacity initialized as specified.

Properties

CanRead

Gets a value indicating whether the current stream supports reading.

CanSeek

Gets a value indicating whether the current stream supports seeking.

CanTimeout

Gets a value that determines whether the current stream can time out.

(Inherited from Stream)
CanWrite

Gets a value indicating whether the current stream supports writing.

Capacity

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

Length

Gets the length of the stream in bytes.

Position

Gets or sets the current position within the stream.

ReadTimeout

Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

(Inherited from Stream)
WriteTimeout

Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(Inherited from Stream)

Methods

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

Begins an asynchronous read operation. (Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

Begins an asynchronous read operation. (Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Begins an asynchronous write operation. (Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Begins an asynchronous write operation. (Consider using WriteAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
Close()

Closes the stream for reading and writing.

Close()

Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed.

(Inherited from Stream)
CopyTo(Stream)

Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.

(Inherited from Stream)
CopyTo(Stream, Int32)

Reads the bytes from the current memory stream and writes them to another stream, using a specified buffer size.

CopyTo(Stream, Int32)

Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied.

(Inherited from Stream)
CopyToAsync(Stream)

Asynchronously reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.

(Inherited from Stream)
CopyToAsync(Stream, CancellationToken)

Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token. Both streams positions are advanced by the number of bytes copied.

(Inherited from Stream)
CopyToAsync(Stream, Int32)

Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied.

(Inherited from Stream)
CopyToAsync(Stream, Int32, CancellationToken)

Asynchronously reads all the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token.

CopyToAsync(Stream, Int32, CancellationToken)

Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token. Both streams positions are advanced by the number of bytes copied.

(Inherited from Stream)
CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateWaitHandle()
Obsolete.
Obsolete.
Obsolete.

Allocates a WaitHandle object.

(Inherited from Stream)
Dispose()

Releases all resources used by the Stream.

(Inherited from Stream)
Dispose(Boolean)

Releases the unmanaged resources used by the MemoryStream class and optionally releases the managed resources.

Dispose(Boolean)

Releases the unmanaged resources used by the Stream and optionally releases the managed resources.

(Inherited from Stream)
DisposeAsync()

Asynchronously releases the unmanaged resources used by the Stream.

(Inherited from Stream)
EndRead(IAsyncResult)

Waits for the pending asynchronous read to complete. (Consider using ReadAsync(Byte[], Int32, Int32, CancellationToken) instead.)

EndRead(IAsyncResult)

Waits for the pending asynchronous read to complete. (Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
EndWrite(IAsyncResult)

Ends an asynchronous write operation. (Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

EndWrite(IAsyncResult)

Ends an asynchronous write operation. (Consider using WriteAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Flush()

Overrides the Flush() method so that no action is performed.

FlushAsync()

Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(Inherited from Stream)
FlushAsync(CancellationToken)

Asynchronously clears all buffers for this stream, and monitors cancellation requests.

FlushAsync(CancellationToken)

Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

(Inherited from Stream)
GetBuffer()

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

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ObjectInvariant()

This API supports the product infrastructure and is not intended to be used directly from your code.

Provides support for a Contract.

ObjectInvariant()
Obsolete.

Provides support for a Contract.

(Inherited from Stream)
Read(Byte[], Int32, Int32)

Reads a block of bytes from the current stream and writes the data to a buffer.

Read(Span<Byte>)

Reads a sequence of bytes from the current memory stream and advances the position within the memory stream by the number of bytes read.

Read(Span<Byte>)

When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(Inherited from Stream)
ReadAsync(Byte[], Int32, Int32)

Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(Inherited from Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Byte[], Int32, Int32, CancellationToken)

Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

(Inherited from Stream)
ReadAsync(Memory<Byte>, CancellationToken)

Asynchronously reads a sequence of bytes from the current memory stream, writes the sequence into destination, advances the position within the memory stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Memory<Byte>, CancellationToken)

Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

(Inherited from Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

Reads at least a minimum number of bytes from the current stream and advances the position within the stream by the number of bytes read.

(Inherited from Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

Asynchronously reads at least a minimum number of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

(Inherited from Stream)
ReadByte()

Reads a byte from the current stream.

ReadExactly(Byte[], Int32, Int32)

Reads count number of bytes from the current stream and advances the position within the stream.

(Inherited from Stream)
ReadExactly(Span<Byte>)

Reads bytes from the current stream and advances the position within the stream until the buffer is filled.

(Inherited from Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

Asynchronously reads count number of bytes from the current stream, advances the position within the stream, and monitors cancellation requests.

(Inherited from Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

Asynchronously reads bytes from the current stream, advances the position within the stream until the buffer is filled, and monitors cancellation requests.

(Inherited from Stream)
Seek(Int64, SeekOrigin)

Sets the position within the current stream to the specified value.

SetLength(Int64)

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

ToArray()

Writes the stream contents to a byte array, regardless of the Position property.

ToString()

Returns a string that represents the current object.

(Inherited from Object)
TryGetBuffer(ArraySegment<Byte>)

Returns the array of unsigned bytes from which this stream was created. The return value indicates whether the conversion succeeded.

Write(Byte[], Int32, Int32)

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

Write(ReadOnlySpan<Byte>)

Writes the sequence of bytes contained in source into the current memory stream and advances the current position within this memory stream by the number of bytes written.

Write(ReadOnlySpan<Byte>)

When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(Inherited from Stream)
WriteAsync(Byte[], Int32, Int32)

Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(Inherited from Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

WriteAsync(Byte[], Int32, Int32, CancellationToken)

Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

(Inherited from Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Asynchronously writes the sequence of bytes contained in source into the current memory stream, advances the current position within this memory stream by the number of bytes written, and monitors cancellation requests.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

(Inherited from Stream)
WriteByte(Byte)

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

WriteTo(Stream)

Writes the entire contents of this memory stream to another stream.

Explicit Interface Implementations

IDisposable.Dispose()

Releases all resources used by the Stream.

(Inherited from Stream)

Extension Methods

AsInputStream(Stream)

Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime.

AsOutputStream(Stream)

Converts a managed stream in the .NET for Windows Store apps to an output stream in the Windows Runtime.

AsRandomAccessStream(Stream)

Converts the specified stream to a random access stream.

GetWindowsRuntimeBuffer(MemoryStream)

Returns a Windows.Storage.Streams.IBuffer interface that represents the same memory as the specified memory stream.

GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32)

Returns a Windows.Storage.Streams.IBuffer interface that represents a region within the memory that the specified memory stream represents.

ConfigureAwait(IAsyncDisposable, Boolean)

Configures how awaits on the tasks returned from an async disposable are performed.

Applies to

See also