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 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 ,當前位置會被設定為零。

Note

此類型實 IDisposable 作介面,但實際上沒有資源可處置。 這表示不必直接呼叫 Dispose() 或使用語言結構,如 using(C#)或 Using(Visual Basic)來處理。

使用無符號位元組陣列建立的記憶體串流,提供不可調整大小的資料串流。 使用位元組陣列時,你既不能附加也無法縮減串流,但你可能可以根據輸入建構子的參數修改現有內容。 空的記憶體串流可調整大小,且可寫入與讀取。

如果 MemoryStream 物件被加入 ResX 檔案或 .resources 檔案,執行時呼叫該 GetStream 方法以取得該物件。

如果一個 MemoryStream 物件被序列化成資源檔案,它實際上會被序列化為 UnmanagedMemoryStream。 這種行為提供了更好的效能,也讓它能直接取得資料的指標,而無需經過 Stream 其他方法。

建構函式

名稱 Description
MemoryStream()

初始化一個可擴充容量為零的類別新實例 MemoryStream

MemoryStream(Byte[], Boolean)

根據指定的位元組陣列初始化一個新的不可調整大小的類別實例 MemoryStream ,並設定 CanWrite 了該屬性。

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

根據指定區域的位元組陣列初始化該類別的新 MemoryStream 實例,屬性 CanWrite 設定如指定,並能呼叫 GetBuffer() set。

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

根據指定區域的位元組陣列初始化一個新的不可調整大小類別實例 MemoryStream ,並設定 CanWrite 相應的屬性。

MemoryStream(Byte[], Int32, Int32)

根據指定的位元組陣列區域(索引)初始化該 MemoryStream 類別的新且不可調整大小的實例。

MemoryStream(Byte[])

根據指定的位元組陣列初始化一個新的不可調整大小的 MemoryStream 類別實例。

MemoryStream(Int32)

初始化一個類別的新實例 MemoryStream ,並依規定初始化可擴充容量。

屬性

名稱 Description
CanRead

會得到一個值,表示目前串流是否支援讀取。

CanSeek

會獲得一個值,表示目前串流是否支援尋道。

CanTimeout

取得值,這個值會判斷目前的數據流是否可以逾時。

(繼承來源 Stream)
CanWrite

會得到一個值,表示目前串流是否支援寫入。

Capacity

取得或設定該串流所分配的位元組數。

Length

會取得串流長度(以位元組為單位)。

Position

取得或設定串流中的當前位置。

ReadTimeout

會取得或設定一個以毫秒為單位的值,決定串流在逾時前嘗試讀取的時間長短。

(繼承來源 Stream)
WriteTimeout

取得或設定一個毫秒級的值,決定串流在逾時前嘗試寫入的時間長短。

(繼承來源 Stream)

方法

名稱 Description
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, Int32)

從目前記憶體串流讀取位元組,並依指定緩衝區大小寫入另一串流。

CopyTo(Stream, Int32)

從目前串流讀取位元組,並依指定緩衝區大小寫入另一串流。 兩個串流的位置依複製的位元組數前進。

(繼承來源 Stream)
CopyTo(Stream)

從目前串流讀取位元組,然後寫入另一條串流。 兩個串流的位置依複製的位元組數前進。

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

使用指定的取消標記,以異步方式從目前數據流讀取位元組,並將其寫入另一個數據流。 兩個串流的位置依複製的位元組數前進。

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

非同步讀取目前串流中的所有位元組,並使用指定的緩衝區大小與消除標記寫入另一串流。

CopyToAsync(Stream, Int32, CancellationToken)

非同步地從目前串流讀取位元組,並使用指定的緩衝區大小與取消標記寫入另一串流。 兩個串流的位置依複製的位元組數前進。

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

非同步讀取目前串流的位元組,並以指定的緩衝區大小寫入另一串流。 兩個串流的位置依複製的位元組數前進。

(繼承來源 Stream)
CopyToAsync(Stream)

非同步地從目前串流讀取位元組,然後寫入另一條串流。 兩個串流的位置依複製的位元組數前進。

(繼承來源 Stream)
CreateObjRef(Type)

建立一個物件,包含產生代理伺服器所需的所有相關資訊,用於與遠端物件通訊。

(繼承來源 MarshalByRefObject)
CreateWaitHandle()
已淘汰.

分配一個 WaitHandle 物件。

(繼承來源 Stream)
Dispose()

釋放所有由 Stream.

(繼承來源 Stream)
Dispose(Boolean)

釋放類別使用的 MemoryStream 非管理資源,並可選擇性地釋放受管理資源。

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)

非同步清除此串流的所有緩衝區,並監控取消請求。

GetBuffer()

回傳該串流所產生的無符號位元組陣列。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetLifetimeService()

取得目前控制此實例生命週期政策的終身服務物件。

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

從目前記憶體串流讀取一串位元組,並依讀取位元組數推進記憶體串流中的位置。

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

非同步讀取目前串流的位元組序列,依讀取位元組數前進串流中的位置,並監控取消請求。

ReadAsync(Byte[], Int32, Int32)

非同步讀取當前串流的位元組序列,並依讀取位元組數推進串流中的位置。

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

非同步從目前記憶體串流讀取一串位元組,將該序列寫入 destination,並依讀取位元組數將記憶體串流中的位置推進,並監控取消請求。

ReadByte()

讀取當前串流中的一個位元組。

Seek(Int64, SeekOrigin)

將當前串流中的位置設定為指定的值。

SetLength(Int64)

將目前串流的長度設定為指定的值。

ToArray()

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

ToString()

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

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

回傳該串流所產生的無符號位元組陣列。 傳回值表示轉換是否成功。

Write(Byte[], Int32, Int32)

利用從緩衝區讀取的資料,將一個位元組區塊寫入當前串流。

Write(ReadOnlySpan<Byte>)

將 所 source 包含的位元組序列寫入目前記憶體串流,並依照寫入的位元組數將該記憶體串流中的當前位置往前推進。

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

非同步地將一串位元組寫入目前串流,依照寫入位元組數將該串流中的當前位置前進,並監控取消請求。

WriteAsync(Byte[], Int32, Int32)

非同步地將一串位元組寫入目前串流,並依照寫入的位元組數將該串流中的當前位置往前推進。

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

非同步地將 中的 source 位元組序列寫入目前記憶體串流,將該記憶體串流中寫入的位元組數往前推進位置,並監控取消請求。

WriteByte(Byte)

在當前位置寫入一個位元組。

WriteTo(Stream)

將該記憶體串流的全部內容寫入另一串流。

明確介面實作

名稱 Description
IDisposable.Dispose()

釋放所有由 Stream.

(繼承來源 Stream)

擴充方法

名稱 Description
AsInputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的 Managed 資料流轉換為 Windows 執行時間中的輸入資料流。

AsOutputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的 Managed 資料流轉換為 Windows 執行時間中的輸出資料流。

AsRandomAccessStream(Stream)

將指定的數據流轉換為隨機存取數據流。

ConfigureAwait(IAsyncDisposable, Boolean)

設定如何執行從異步可處置專案傳回的工作等候。

GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32)

退回一台 Windows。Storage.Streams.IBuffer 介面,代表指定記憶體串流所代表的記憶體區域。

GetWindowsRuntimeBuffer(MemoryStream)

退回一台 Windows。Storage.Streams.IBuffer 介面,代表與指定記憶體串流相同的記憶體。

適用於

另請參閱