UnmanagedMemoryStream UnmanagedMemoryStream UnmanagedMemoryStream UnmanagedMemoryStream Class

定義

重要

此 API 不符合 CLS 規範。

從 Managed 程式碼對 Unmanaged 記憶體區塊提供存取。Provides access to unmanaged blocks of memory from managed code.

public ref class UnmanagedMemoryStream : System::IO::Stream
[System.CLSCompliant(false)]
public class UnmanagedMemoryStream : System.IO.Stream
type UnmanagedMemoryStream = class
    inherit Stream
Public Class UnmanagedMemoryStream
Inherits Stream
繼承
UnmanagedMemoryStreamUnmanagedMemoryStreamUnmanagedMemoryStreamUnmanagedMemoryStream
衍生
屬性

範例

下列程式碼範例示範如何讀取和寫入 unmanaged 的記憶體使用UnmanagedMemoryStream類別。The following code example demonstrates how to read from and write to unmanaged memory using the UnmanagedMemoryStream class. 配置和解除配置使用的 unmanaged 記憶體區塊Marshal類別。A block of unmanaged memory is allocated and de-allocated using the Marshal class.


// Note: you must compile this sample using the unsafe flag.
// From the command line, type the following: csc sample.cs /unsafe

using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;

unsafe class TestWriter
{
    
    static void Main()
	{
		
            // Create some data to read and write.
            byte[] message = UnicodeEncoding.Unicode.GetBytes("Here is some data.");

	    // Allocate a block of unmanaged memory and return an IntPtr object.	
            IntPtr memIntPtr = Marshal.AllocHGlobal(message.Length);

            // Get a byte pointer from the IntPtr object.
            byte* memBytePtr = (byte*) memIntPtr.ToPointer();

            // Create an UnmanagedMemoryStream object using a pointer to unmanaged memory.
            UnmanagedMemoryStream writeStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Write);

            // Write the data.
            writeStream.Write(message, 0, message.Length);

            // Close the stream.
            writeStream.Close();

            // Create another UnmanagedMemoryStream object using a pointer to unmanaged memory.
            UnmanagedMemoryStream readStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Read);

	    // Create a byte array to hold data from unmanaged memory.
            byte[] outMessage = new byte[message.Length];

            // Read from unmanaged memory to the byte array.
            readStream.Read(outMessage, 0, message.Length);

            // Close the stream.
            readStream.Close();

            // Display the data to the console.
            Console.WriteLine(UnicodeEncoding.Unicode.GetString(outMessage));

            // Free the block of unmanaged memory.
            Marshal.FreeHGlobal(memIntPtr);

            Console.ReadLine();
    }
}

備註

這個類別支援使用現有的資料流為基礎模型的 unmanaged 記憶體的存取權,而且不需要在 unmanaged 記憶體中的內容會複製到堆積。This class supports access to unmanaged memory using the existing stream-based model and does not require that the contents in the unmanaged memory be copied to the heap.

注意

此類型會實作 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.

建構函式

UnmanagedMemoryStream() UnmanagedMemoryStream() UnmanagedMemoryStream() UnmanagedMemoryStream()

初始化 UnmanagedMemoryStream 類別的新執行個體。Initializes a new instance of the UnmanagedMemoryStream class.

UnmanagedMemoryStream(Byte*, Int64) UnmanagedMemoryStream(Byte*, Int64) UnmanagedMemoryStream(Byte*, Int64) UnmanagedMemoryStream(Byte*, Int64)

使用指定的位置和記憶體長度,初始化 UnmanagedMemoryStream 類別的新執行個體。Initializes a new instance of the UnmanagedMemoryStream class using the specified location and memory length.

UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess) UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess) UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess) UnmanagedMemoryStream(Byte*, Int64, Int64, FileAccess)

使用指定的位置、記憶體長度、記憶體總數和檔案存取值,初始化 UnmanagedMemoryStream 類別的新執行個體。Initializes a new instance of the UnmanagedMemoryStream class using the specified location, memory length, total amount of memory, and file access values.

UnmanagedMemoryStream(SafeBuffer, Int64, Int64) UnmanagedMemoryStream(SafeBuffer, Int64, Int64) UnmanagedMemoryStream(SafeBuffer, Int64, Int64) UnmanagedMemoryStream(SafeBuffer, Int64, Int64)

在安全緩衝區中使用指定的位移和長度,初始化 UnmanagedMemoryStream 類別的新執行個體。Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset and length.

UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess) UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess) UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess) UnmanagedMemoryStream(SafeBuffer, Int64, Int64, FileAccess)

在安全緩衝區中使用指定的位移、長度和檔案存取,初始化 UnmanagedMemoryStream 類別的新執行個體。Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset, length, and file access.

屬性

CanRead CanRead CanRead CanRead

取得值,指出資料流是否支援讀取。Gets a value indicating whether a stream supports reading.

CanSeek CanSeek CanSeek CanSeek

取得值,指出資料流是否支援搜尋。Gets a value indicating whether a stream supports seeking.

CanTimeout CanTimeout CanTimeout CanTimeout

取得值,該值判斷目前的資料流是否可以逾時。Gets a value that determines whether the current stream can time out.

(Inherited from Stream)
CanWrite CanWrite CanWrite CanWrite

取得值,指出物件是否支援寫入。Gets a value indicating whether a stream supports writing.

Capacity Capacity Capacity Capacity

取得資料流長度 (大小) 或指派給資料流的記憶體總量 (容量)。Gets the stream length (size) or the total amount of memory assigned to a stream (capacity).

Length Length Length Length

取得資料流中資料的長度。Gets the length of the data in a stream.

Position Position Position Position

取得或設定資料流中目前的位置。Gets or sets the current position in a stream.

PositionPointer PositionPointer PositionPointer PositionPointer

依據資料流中的目前位置,取得或設定資料流的位元組指標。Gets or sets a byte pointer to a stream based on the current position in the stream.

ReadTimeout ReadTimeout ReadTimeout ReadTimeout

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

(Inherited from Stream)
WriteTimeout WriteTimeout WriteTimeout WriteTimeout

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

(Inherited from Stream)

方法

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

開始非同步的讀取作業。Begins an asynchronous read operation. (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。)(Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的寫入作業。Begins an asynchronous write operation. (請考慮用 WriteAsync(Byte[], Int32, Int32) 替代。)(Consider using WriteAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
Close() Close() Close() Close()

關閉目前資料流和釋放與目前資料流相關聯的任何資源 (例如通訊端和檔案控制代碼)。Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. 請確定正確地處置資料流,而非呼叫這個方法。Instead of calling this method, ensure that the stream is properly disposed.

(Inherited from Stream)
CopyTo(Stream) CopyTo(Stream) CopyTo(Stream) CopyTo(Stream)

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

(Inherited from Stream)
CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32)

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

(Inherited from Stream)
CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream)

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

(Inherited from Stream)
CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken)

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

(Inherited from Stream)
CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32)

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

(Inherited from Stream)
CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken)

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

(Inherited from Stream)
CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

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

(Inherited from MarshalByRefObject)
CreateWaitHandle() CreateWaitHandle() CreateWaitHandle() CreateWaitHandle()

配置 WaitHandle 物件。Allocates a WaitHandle object.

(Inherited from Stream)
Dispose() Dispose() Dispose() Dispose()

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

(Inherited from Stream)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

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

DisposeAsync() DisposeAsync() DisposeAsync() DisposeAsync()

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

(Inherited from Stream)
EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult)

等候暫止的非同步讀取完成。Waits for the pending asynchronous read to complete. (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。)(Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult)

結束非同步的寫入作業。Ends an asynchronous write operation. (請考慮用 WriteAsync(Byte[], Int32, Int32) 替代。)(Consider using WriteAsync(Byte[], Int32, Int32) instead.)

(Inherited from Stream)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
Flush() Flush() Flush() Flush()

覆寫 Flush() 方法,以便不執行任何動作。Overrides the Flush() method so that no action is performed.

FlushAsync() FlushAsync() FlushAsync() FlushAsync()

以非同步的方式清除這個資料流的所有緩衝區,並造成所有緩衝資料都寫入基礎裝置。Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(Inherited from Stream)
FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken)

覆寫 FlushAsync(CancellationToken) 方法,以取消指定的作業,但不執行其他任何動作。Overrides the FlushAsync(CancellationToken) method so that the operation is cancelled if specified, but no other action is performed.

從 .NET Framework 4.6 開始可供使用Available starting in .NET Framework 4.6

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

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

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
Initialize(Byte*, Int64, Int64, FileAccess) Initialize(Byte*, Int64, Int64, FileAccess) Initialize(Byte*, Int64, Int64, FileAccess) Initialize(Byte*, Int64, Int64, FileAccess)

使用 Unmanaged 記憶體位置的指標,初始化 UnmanagedMemoryStream 類別的新執行個體。Initializes a new instance of the UnmanagedMemoryStream class by using a pointer to an unmanaged memory location.

Initialize(SafeBuffer, Int64, Int64, FileAccess) Initialize(SafeBuffer, Int64, Int64, FileAccess) Initialize(SafeBuffer, Int64, Int64, FileAccess) Initialize(SafeBuffer, Int64, Int64, FileAccess)

在安全緩衝區中使用指定的位移、長度和檔案存取,初始化 UnmanagedMemoryStream 類別的新執行個體。Initializes a new instance of the UnmanagedMemoryStream class in a safe buffer with a specified offset, length, and file access.

InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

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

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

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

(Inherited from MarshalByRefObject)
ObjectInvariant() ObjectInvariant() ObjectInvariant() ObjectInvariant()

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

(Inherited from Stream)
Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)

將指定的位元組數讀入指定的陣列。Reads the specified number of bytes into the specified array.

Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>)
ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) 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.

(Inherited from Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken)

將指定的位元組數以非同步方式讀入指定的陣列。Asynchronously reads the specified number of bytes into the specified array.

從 .NET Framework 4.6 開始可供使用Available starting in .NET Framework 4.6

ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken)
ReadByte() ReadByte() ReadByte() ReadByte()

從資料流讀取一個位元組,並將資料流的位置推進一個位元組;如果在資料流結尾,則傳回 -1。Reads a byte from a stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.

Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin)

將目前資料流的目前位置設為指定值。Sets the current position of the current stream to the given value.

SetLength(Int64) SetLength(Int64) SetLength(Int64) SetLength(Int64)

將資料流長度設為指定值。Sets the length of a stream to a specified value.

ToString() ToString() ToString() ToString()

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

(Inherited from Object)
Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32)

使用緩衝區的資料,將位元組區塊寫入目前的資料流。Writes a block of bytes to the current stream using data from a buffer.

Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>)
WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) 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.

(Inherited from Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) 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.

從 .NET Framework 4.6 開始可供使用Available starting in .NET Framework 4.6

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)
WriteByte(Byte) WriteByte(Byte) WriteByte(Byte) WriteByte(Byte)

寫入一個位元組到檔案資料流中的目前位置。Writes a byte to the current position in the file stream.

明確介面實作

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

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

(Inherited from Stream)

Extension Methods

AsInputStream(Stream) AsInputStream(Stream) AsInputStream(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) AsOutputStream(Stream) AsOutputStream(Stream) 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) AsRandomAccessStream(Stream) AsRandomAccessStream(Stream) AsRandomAccessStream(Stream)

將指定的資料流轉換為隨機存取資料流。Converts the specified stream to a random access stream.

適用於