Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

MemoryStream Class

Creates a stream whose backing store is memory.

For a list of all members of this type, see MemoryStream Members.

System.Object
   System.MarshalByRefObject
      System.IO.Stream
         System.IO.MemoryStream

[Visual Basic]
<Serializable>
Public Class MemoryStream
   Inherits Stream
[C#]
[Serializable]
public class MemoryStream : Stream
[C++]
[Serializable]
public __gc class MemoryStream : public Stream
[JScript]
public
   Serializable
class MemoryStream extends Stream

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Remarks

For an example of creating a file and writing text to a file, see Writing Text to a File. For an example of reading text from a file, see Reading Text from a File. For an example of reading from and writing to a binary file, see Reading and Writing to a Newly Created Data File.

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 that is initialized upon creation of a MemoryStream object, or the array can be created as empty. 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 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.

Memory streams created with an unsigned byte array provide a non-resizable stream view of the data, and can only be written to. 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.

Example

[Visual Basic, C#, C++] The following code example shows how to read and write data using memory as a backing store.

[Visual Basic] 
Imports System
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.InvalidPathChars)

        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

[C#] 
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.InvalidPathChars);

        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++] = 
                    Convert.ToByte(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);
        }
    }
}

[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::IO;
using namespace System::Text;

void main()
{
    int count;
    Byte byteArray __gc[];
    Char charArray __gc[];
    UnicodeEncoding* uniEncoding = new UnicodeEncoding();

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

    MemoryStream* memStream = 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++]);
        }

        // Write the stream properties to the console.
        Console::WriteLine(S"Capacity = {0}, Length = {1}, "
            S"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 = new Byte __gc[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 = 
            new Char __gc[uniEncoding->GetCharCount(
            byteArray, 0, count)];
        uniEncoding->GetDecoder()->GetChars(
            byteArray, 0, count, charArray, 0);
        Console::WriteLine(charArray);
    }
    __finally
    {
        memStream->Close();
    }
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.IO

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: Mscorlib (in Mscorlib.dll)

See Also

MemoryStream Members | System.IO Namespace | Working with I/O | Reading Text from a File | Writing Text to a File

Show:
© 2014 Microsoft