UnmanagedMemoryStream.ReadByte 方法

定義

從資料流讀取一個位元組,並將資料流的位置推進一個位元組;如果在資料流結尾,則傳回 -1。

public:
 override int ReadByte();
public override int ReadByte ();
override this.ReadByte : unit -> int
Public Overrides Function ReadByte () As Integer

傳回

轉換成 Int32 物件的不帶正負號位元組;如果在資料流結尾,則為 -1。

例外狀況

資料流已關閉。

基礎記憶體不支援讀取。

-或-

目前位置位於資料流結尾。

範例

下列程式代碼範例示範如何使用 類別讀取和寫入 Unmanaged 記憶體 UnmanagedMemoryStream 。 Unmanaged 記憶體區塊會使用 Marshal 類別來配置和取消配置。 在此範例中, UnmanagedMemoryStream 對象會傳遞至方法,在嘗試讀取和顯示內容至主控台之前先檢查 CanRead 屬性。

// 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.Runtime.InteropServices;
using System.Text;

unsafe class Program
{
    static void Main()
    {
        // Create some data to write.
        byte[] text = UnicodeEncoding.Unicode.GetBytes("Data to write.");

        // Allocate a block of unmanaged memory.
        IntPtr memIntPtr = Marshal.AllocHGlobal(text.Length);

        // Get a byte pointer from the unmanaged memory block.
        byte* memBytePtr = (byte*)memIntPtr.ToPointer();

        UnmanagedMemoryStream writeStream =
            new UnmanagedMemoryStream(
            memBytePtr, text.Length, text.Length, FileAccess.Write);

        // Write the data.
        WriteToStream(writeStream, text);

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

        // Create another UnmanagedMemoryStream for reading.
        UnmanagedMemoryStream readStream =
            new UnmanagedMemoryStream(memBytePtr, text.Length);

        // Display the contents of the stream to the console.
        PrintStream(readStream);

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

        // Free up the unmanaged memory.
        Marshal.FreeHGlobal(memIntPtr);
    }

    public static void WriteToStream(UnmanagedMemoryStream writeStream, byte[] text)
    {
        // Verify that the stream is writable:
        // By default, UnmanagedMemoryStream objects do not have write access,
        // write access must be set explicitly.
        if (writeStream.CanWrite)
        {
            // Write the data, byte by byte
            for (int i = 0; i < writeStream.Length; i++)
            {
                writeStream.WriteByte(text[i]);
            }
        }
    }

    public static void PrintStream(UnmanagedMemoryStream readStream)
    {
        byte[] text = new byte[readStream.Length];
        // Verify that the stream is writable:
        // By default, UnmanagedMemoryStream objects do not have write access,
        // write access must be set explicitly.
        if (readStream.CanRead)
        {
            // Write the data, byte by byte
            for (int i = 0; i < readStream.Length; i++)
            {
                text[i] = (byte)readStream.ReadByte();
            }
        }

        Console.WriteLine(UnicodeEncoding.Unicode.GetString(text));
    }
}

備註

使用這個方法從數據流傳回整數值。

適用於