FileStream.ReadByte 方法

定義

從檔案讀取一個位元組,並將讀取位置前移一個位元組。

C#
public override int ReadByte ();

傳回

轉換為 Int32 的位元組,如果已經到達資料流的末端,則為 -1。

例外狀況

目前的資料流不支援讀取。

目前的資料流已關閉。

範例

下列程式代碼範例示範如何將數據寫入檔案、位元組位元組,然後確認數據已正確寫入。

C#
using System;
using System.IO;

class FStream
{
    static void Main()
    {
        const string fileName = "Test#@@#.dat";

        // Create random data to write to the file.
        byte[] dataArray = new byte[100000];
        new Random().NextBytes(dataArray);

        using(FileStream
            fileStream = new FileStream(fileName, FileMode.Create))
        {
            // Write the data to the file, byte by byte.
            for(int i = 0; i < dataArray.Length; i++)
            {
                fileStream.WriteByte(dataArray[i]);
            }

            // Set the stream position to the beginning of the file.
            fileStream.Seek(0, SeekOrigin.Begin);

            // Read and verify the data.
            for(int i = 0; i < fileStream.Length; i++)
            {
                if(dataArray[i] != fileStream.ReadByte())
                {
                    Console.WriteLine("Error writing data.");
                    return;
                }
            }
            Console.WriteLine("The data was written to {0} " +
                "and verified.", fileStream.Name);
        }
    }
}

備註

這個方法會覆寫 ReadByte

備註

CanRead使用屬性來判斷目前實例是否支援讀取。 如需詳細資訊,請參閱 CanRead

給繼承者的注意事項

上的 Stream 預設實作會建立新的單一位元組數組,然後呼叫 Read(Byte[], Int32, Int32)。 雖然這正式正確,但效率不佳。 任何具有內部緩衝區的數據流都應該覆寫這個方法,並提供更有效率的版本來直接讀取緩衝區,以避免每次呼叫時都配置額外的數位。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另請參閱