MemoryStream 類別

定義

建立支援的存放區為記憶體的資料流。Creates a stream whose backing store is memory.

public ref class MemoryStream : System::IO::Stream
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class MemoryStream : System.IO.Stream
type MemoryStream = class
    inherit Stream
Public Class MemoryStream
Inherits Stream
繼承
屬性

範例

下列程式碼範例示範如何使用記憶體作為備份存放區來讀取和寫入資料。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++] =
                    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);
        }
    }
}
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

備註

資料流程的目前位置是下一個讀取或寫入作業可能發生的位置。The current position of a stream is the position at which the next read or write operation could take place. 您可以透過Seek方法來抓取或設定目前的位置。The current position can be retrieved or set through the Seek method. 建立的新實例MemoryStream時,目前的位置會設定為零。When a new instance of MemoryStream is created, the current position is set to zero.

注意

此類型會實作 IDisposable 介面,但實際上沒有任何要處置的資源。This type implements the IDisposable interface, but does not actually have any resources to dispose. 這表示其處置方式不一定要直接呼叫 Dispose() 或使用語言建構,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。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.

如果將MemoryStream物件加入至 ResX 檔案或 .resources 檔案,請在執行時間GetStream呼叫方法以抓取它。If a MemoryStream object is added to a ResX file or a .resources file, call the GetStream method at runtime to retrieve it.

如果物件序列化為資源檔,它實際上會序列化UnmanagedMemoryStream為。 MemoryStreamIf a MemoryStream object is serialized to a resource file it will actually be serialized as an UnmanagedMemoryStream. 這個行為可提供較佳的效能,以及直接取得資料指標的能力,而不需要經過Stream方法。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.

建構函式

MemoryStream()

使用初始化為零的可擴展容量,初始化 MemoryStream 類別的新執行個體。Initializes a new instance of the MemoryStream class with an expandable capacity initialized to zero.

MemoryStream(Byte[])

根據指定的位元組陣列,初始化 MemoryStream 類別之不可調整大小的執行個體。Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array.

MemoryStream(Byte[], Boolean)

根據具有指定的 MemoryStream 屬性設定之位元組陣列,來初始化 CanWrite 類別之新的不可調整大小的執行個體。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)

根據位元組陣列的指定區域 (索引),來初始化 MemoryStream 類別之新的不可調整大小的執行個體。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)

根據位元組陣列的指定區域 (且該區域使用依指定所設定的 MemoryStream 屬性),來初始化 CanWrite 類別之新的不可調整大小的執行個體。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)

根據指定的位元組陣列區域 (且該區域使用依指定所設定的 MemoryStream 屬性和依指定所設定的呼叫 CanWrite 的能力),來初始化 GetBuffer() 類別的新執行個體。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)

使用初始化為指定的可擴展容量,初始化 MemoryStream 類別的新執行個體。Initializes a new instance of the MemoryStream class with an expandable capacity initialized as specified.

屬性

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.

(繼承來源 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.

(繼承來源 Stream)
WriteTimeout

取得或設定值 (以毫秒為單位),這個值決定在逾時前資料流將嘗試寫入多長時間。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(繼承來源 Stream)

方法

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

關閉資料流以讀取和寫入。Closes the stream for reading and writing.

CopyTo(Stream)

從目前資料流讀取位元組,並將其寫入另一個資料流中。Reads the bytes from the current stream and writes them to another stream.

(繼承來源 Stream)
CopyTo(Stream, Int32)
CopyToAsync(Stream)

以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Asynchronously reads the bytes from the current stream and writes them to another stream.

(繼承來源 Stream)
CopyToAsync(Stream, CancellationToken)

使用指定的取消權杖,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

(繼承來源 Stream)
CopyToAsync(Stream, Int32)

使用指定的緩衝區大小,以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(繼承來源 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.

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)
CreateWaitHandle()

配置 WaitHandle 物件。Allocates a WaitHandle object.

(繼承來源 Stream)
Dispose()

釋放 Stream 所使用的所有資源。Releases all resources used by the Stream.

(繼承來源 Stream)
Dispose(Boolean)

釋放 MemoryStream 類別所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the MemoryStream class and optionally releases the managed resources.

DisposeAsync()

以非同步方式釋放 Stream 使用的不受控資源。Asynchronously releases the unmanaged resources used by the Stream.

(繼承來源 Stream)
EndRead(IAsyncResult)
EndWrite(IAsyncResult)
Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
Flush()

覆寫 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.

(繼承來源 Stream)
FlushAsync(CancellationToken)

非同步清除這個資料流的所有緩衝區,並監視取消要求。Asynchronously clears all buffers for this stream, and monitors cancellation requests.

GetBuffer()

傳回用於建立這個資料流之不帶正負號位元組的陣列。Returns the array of unsigned bytes from which this stream was created.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(繼承來源 MarshalByRefObject)
ObjectInvariant()

提供 Contract 的支援。Provides support for a Contract.

Read(Byte[], Int32, Int32)

從目前的資料流讀取位元組區塊,並且將資料寫入緩衝區。Reads a block of bytes from the current stream and writes the data to a buffer.

Read(Span<Byte>)
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.

(繼承來源 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(Memory<Byte>, CancellationToken)
ReadByte()

從目前的資料流讀取位元組。Reads a byte from the current 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()

不論 Position 屬性為何,將資料流內容寫入位元組陣列。Writes the stream contents to a byte array, regardless of the Position property.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 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>)
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.

(繼承來源 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(ReadOnlyMemory<Byte>, CancellationToken)
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.

明確介面實作

IDisposable.Dispose()

釋放 Stream 所使用的所有資源。Releases all resources used by the Stream.

(繼承來源 Stream)

擴充方法

AsInputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的受控資料流轉換成 Windows 執行階段中的輸入資料流。Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime.

AsOutputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的受控資料流轉換成 Windows 執行階段中的輸出資料流。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)

傳回代表與指定之記憶體串流相同之記憶體的 Windows.Storage.Streams.IBuffer 介面。Returns a Windows.Storage.Streams.IBuffer interface that represents the same memory as the specified memory stream.

GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32)

傳回 Windows.Storage.Streams.IBuffer 介面,表示記憶體內指定記憶體資料流所代表的區域。Returns a Windows.Storage.Streams.IBuffer interface that represents a region within the memory that the specified memory stream represents.

適用於

另請參閱