MemoryStream 類別

定義

建立支援的存放區為記憶體的資料流。

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
繼承
MemoryStream
繼承
屬性

範例

下列程式碼範例示範如何使用記憶體作為備份存放區來讀取和寫入資料。

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

備註

資料流程的目前位置是下一個讀取或寫入作業可能發生的位置。 您可以透過 Seek 方法擷取或設定目前的位置。 建立 的新實例 MemoryStream 時,目前的位置會設定為零。

注意

此類型會實作 IDisposable 介面,但實際上沒有任何要處置的資源。 這表示其處置方式不一定要直接呼叫 Dispose() 或使用語言建構,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。

使用未簽署位元組陣列所建立的記憶體資料流程會提供不可調整大小的資料流程。 使用位元組陣列時,您無法附加至 或壓縮資料流程,不過您可以根據傳入建構函式的參數來修改現有的內容。 空的記憶體資料流程可調整大小,而且可以寫入和讀取。

MemoryStream如果物件新增至 ResX 檔案或 .resources 檔案,請在執行時間呼叫 GetStream 方法以擷取它。

MemoryStream如果物件序列化為資源檔,則實際上會序列化為 UnmanagedMemoryStream 。 此行為可提供更佳的效能,以及直接取得資料的指標的能力,而不需要通過 Stream 方法。

建構函式

MemoryStream()

使用初始化為零的可擴展容量,初始化 MemoryStream 類別的新執行個體。

MemoryStream(Byte[])

根據指定的位元組陣列,初始化 MemoryStream 類別之不可調整大小的執行個體。

MemoryStream(Byte[], Boolean)

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

MemoryStream(Byte[], Int32, Int32)

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

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

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

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

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

MemoryStream(Int32)

使用初始化為指定的可擴展容量,初始化 MemoryStream 類別的新執行個體。

屬性

CanRead

取得表示目前資料流是否支援讀取的值。

CanSeek

取得表示目前資料流是否支援搜尋的值。

CanTimeout

取得值,該值判斷目前的資料流是否可以逾時。

(繼承來源 Stream)
CanWrite

取得表示目前資料流是否支援寫入的值。

Capacity

取得或設定配置給這個資料流的位元組數目。

Length

取得資料流的長度,以位元組為單位。

Position

取得或設定資料流中目前的位置。

ReadTimeout

取得或設定值 (以毫秒為單位),該值決定資料流在逾時前將嘗試讀取多長時間。

(繼承來源 Stream)
WriteTimeout

取得或設定毫秒值,該值決定在逾時前資料流將嘗試寫入多長時間。

(繼承來源 Stream)

方法

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

開始非同步的讀取作業。 (請考慮用 ReadAsync(Byte[], Int32, Int32, CancellationToken) 替代。)

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

開始非同步的讀取作業。 (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。)

(繼承來源 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的寫入作業。 (請考慮用 WriteAsync(Byte[], Int32, Int32, CancellationToken) 替代。)

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

開始非同步的寫入作業。 (請考慮用 WriteAsync(Byte[], Int32, Int32) 替代。)

(繼承來源 Stream)
Close()

關閉資料流以讀取和寫入。

Close()

關閉目前資料流和釋放與目前資料流相關聯的任何資源 (例如通訊端和檔案控制代碼)。 請確定正確地處置資料流,而非呼叫這個方法。

(繼承來源 Stream)
CopyTo(Stream)

從目前資料流讀取位元組,並將其寫入另一個資料流中。

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

使用指定的緩衝區大小,從目前記憶體資料流讀取位元組,並將其寫入至另一個資料流。

CopyTo(Stream, Int32)

使用指定的緩衝區大小,從目前資料流讀取所有位元組,並將其寫入另一個資料流中。

(繼承來源 Stream)
CopyToAsync(Stream)

以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。

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

使用指定的取消權杖,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。

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

使用指定的緩衝區大小,以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。

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

使用指定的緩衝區大小和取消語彙基元,以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流。

CopyToAsync(Stream, Int32, CancellationToken)

使用指定的緩衝區大小和取消語彙基元,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。

(繼承來源 Stream)
CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。

(繼承來源 MarshalByRefObject)
CreateWaitHandle()
已過時。
已過時。

配置 WaitHandle 物件。

(繼承來源 Stream)
Dispose()

釋放 Stream 所使用的所有資源。

(繼承來源 Stream)
Dispose(Boolean)

釋放 MemoryStream 類別所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

Dispose(Boolean)

釋放 Stream 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

(繼承來源 Stream)
DisposeAsync()

以非同步方式釋放 Stream 使用的不受控資源。

(繼承來源 Stream)
EndRead(IAsyncResult)

等候暫止的非同步讀取完成。 (請考慮用 ReadAsync(Byte[], Int32, Int32, CancellationToken) 替代。)

EndRead(IAsyncResult)

等候暫止的非同步讀取完成。 (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。)

(繼承來源 Stream)
EndWrite(IAsyncResult)

結束非同步的寫入作業。 (請考慮用 WriteAsync(Byte[], Int32, Int32, CancellationToken) 替代。)

EndWrite(IAsyncResult)

結束非同步的寫入作業。 (請考慮用 WriteAsync(Byte[], Int32, Int32) 替代。)

(繼承來源 Stream)
Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Flush()

覆寫 Flush() 方法,以便不執行任何動作。

FlushAsync()

以非同步的方式清除這個資料流的所有緩衝區,並造成所有緩衝資料都寫入基礎裝置。

(繼承來源 Stream)
FlushAsync(CancellationToken)

非同步清除這個資料流的所有緩衝區,並監視取消要求。

FlushAsync(CancellationToken)

以非同步的方式清除這個資料流的所有緩衝區,造成所有緩衝資料都寫入基礎裝置,並且監視取消要求。

(繼承來源 Stream)
GetBuffer()

傳回用於建立這個資料流之不帶正負號位元組的陣列。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetLifetimeService()
已過時。

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。

(繼承來源 MarshalByRefObject)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
InitializeLifetimeService()
已過時。

取得存留期服務物件,以控制這個執行個體的存留期原則。

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。

(繼承來源 MarshalByRefObject)
ObjectInvariant()

此 API 支援此產品基礎結構,但無法直接用於程式碼之中。

提供 Contract 的支援。

ObjectInvariant()
已過時。

提供 Contract 的支援。

(繼承來源 Stream)
Read(Byte[], Int32, Int32)

從目前的資料流讀取位元組區塊,並且將資料寫入緩衝區。

Read(Span<Byte>)

從目前的記憶體資料流讀取位元組序列,並將記憶體資料流中的位置依讀取的位元組數向前移動。

Read(Span<Byte>)

當在衍生類別中覆寫時,自目前資料流讀取一連串的位元組,並依所讀取的位元組數目進階資料流中的位置。

(繼承來源 Stream)
ReadAsync(Byte[], Int32, Int32)

以非同步的方式從目前的資料流讀取位元組序列,並依讀取的位元組數將資料流中的位置往前移。

(繼承來源 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。

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

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。

(繼承來源 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

以非同步方式從目前的記憶體資料流讀取位元組序列、將此序列寫入至 destination、將記憶體資料流中的位置依讀取的位元組數向前移動,並監視取消要求。

ReadAsync(Memory<Byte>, CancellationToken)

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。

(繼承來源 Stream)
ReadByte()

從目前的資料流讀取位元組。

Seek(Int64, SeekOrigin)

將目前資料流中的位置設定為指定的數值。

SetLength(Int64)

將目前資料流的長度設定為指定的數值。

ToArray()

不論 Position 屬性為何,將資料流內容寫入位元組陣列。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)
TryGetBuffer(ArraySegment<Byte>)

傳回用於建立這個資料流之不帶正負號位元組的陣列。 指出轉換是否成功的傳回值。

Write(Byte[], Int32, Int32)

使用讀取自緩衝區的資料,將位元組區塊寫入至目前的資料流。

Write(ReadOnlySpan<Byte>)

source 中包含的位元組序列寫入目前的記憶體資料流,並將記憶體資料流中目前的位置依寫入的位元組數往前移。

Write(ReadOnlySpan<Byte>)

在衍生類別中覆寫時,將一連串的位元組寫入目前的資料流,並且由這個資料流中目前的位置前移寫入的位元組數目。

(繼承來源 Stream)
WriteAsync(Byte[], Int32, Int32)

以非同步的方式將位元組序列寫入至目前的資料流,並依寫入的位元組數將資料流中目前的位置往前移。

(繼承來源 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。

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

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。

(繼承來源 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以非同步方式將 source 中包含的位元組序列寫入至目前的記憶體資料流、將此記憶體資料流中目前的位置依寫入的位元組數向前移動,並監視取消要求。

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。

(繼承來源 Stream)
WriteByte(Byte)

寫入位元組至資料流目前位置。

WriteTo(Stream)

將這個記憶體資料流的整個內容寫入另一個資料流。

明確介面實作

IDisposable.Dispose()

釋放 Stream 所使用的所有資源。

(繼承來源 Stream)

擴充方法

AsInputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的受控資料流轉換成 Windows 執行階段中的輸入資料流。

AsOutputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的受控資料流轉換成 Windows 執行階段中的輸出資料流。

AsRandomAccessStream(Stream)

將指定的資料流轉換為隨機存取資料流。

GetWindowsRuntimeBuffer(MemoryStream)

傳回代表與指定之記憶體串流相同之記憶體的 Windows.Storage.Streams.IBuffer 介面。

GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32)

傳回 Windows.Storage.Streams.IBuffer 介面,表示記憶體內指定記憶體資料流所代表的區域。

ConfigureAwait(IAsyncDisposable, Boolean)

設定如何執行從非同步可處置項目傳回的工作 await。

適用於

另請參閱