Export (0) Print
Expand All

MemoryStream Class

Creates a stream whose backing store is memory.

Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)

[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class MemoryStream : Stream
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class MemoryStream extends Stream
SerializableAttribute 
ComVisibleAttribute(true) 
public class MemoryStream extends Stream
Not applicable.

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.

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.

Windows Mobile 2003 for Pocket PC, Windows Mobile 2003 for Smartphone, Windows CE Platform Note: In Windows CE, a memory stream pasted from the Clipboard can have a slightly larger size than the memory stream copied to the Clipboard, because extra bytes can be appended to the end of the original memory stream. To accurately retrieve the memory stream either prefix the object with its size to determine how to receive it, or copy a DataObject to the Clipboard containing the memory stream and a string value of its size.

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

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);
        }
    }
}

import System.*;
import System.IO.*;
import System.Text.*;

class MemStream
{   
    public static void main(String[] args)
    {
        int count;
        ubyte byteArray[];
        char charArray[];
        UnicodeEncoding uniEncoding =  new UnicodeEncoding();

        // Create the data to write to the stream.
        ubyte firstString[] = uniEncoding.GetBytes(
            "Invalid file path characters are: ");
        ubyte secondString[] = 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(
                "Capacity = {0}, Length = {1}, Position = {2}\n", 
                (new Integer( memStream.get_Capacity())).ToString(),
                (new Long ( memStream.get_Length())).ToString(),
                (new Long ( memStream.get_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 ubyte[(int)memStream.get_Length()];
            count = memStream.Read(byteArray, 0, 20);

            // Read the remaining bytes, byte by byte.
            while ((count < memStream.get_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);
        }
        finally {
            memStream.Dispose();
        }
    }//main
} //MemStream

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

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

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0

Community Additions

ADD
Show:
© 2014 Microsoft