英語で読む

次の方法で共有


BinaryReader.ReadByte メソッド

定義

現在のストリームから次のバイトを読み取り、ストリームの現在位置を 1 バイトだけ進めます。

public virtual byte ReadByte ();

戻り値

現在のストリームから読み取った次のバイト。

例外

ストリームの末尾に到達しました。

ストリームは閉じられています。

I/O エラーが発生しました。

次のコード例は、メモリをバッキング ストアとして使用してバイナリ データを書き込み、データが正しく書き込まれたことを確認する方法を示しています。

using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i = 0;

        // Create random data to write to the stream.
        byte[] writeArray = new byte[1000];
        new Random().NextBytes(writeArray);

        BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
        BinaryReader binReader =
            new BinaryReader(binWriter.BaseStream);

        try
        {
            // Write the data to the stream.
            Console.WriteLine("Writing the data.");
            for(i = 0; i < writeArray.Length; i++)
            {
                binWriter.Write(writeArray[i]);
            }

            // Set the stream position to the beginning of the stream.
            binReader.BaseStream.Position = 0;

            // Read and verify the data from the stream.
            for(i = 0; i < writeArray.Length; i++)
            {
                if(binReader.ReadByte() != writeArray[i])
                {
                    Console.WriteLine("Error writing the data.");
                    return;
                }
            }
            Console.WriteLine("The data was written and verified.");
        }

        // Catch the EndOfStreamException and write an error message.
        catch(EndOfStreamException e)
        {
            Console.WriteLine("Error writing the data.\n{0}",
                e.GetType().Name);
        }
    }
}

注釈

BinaryReader は、読み取りが失敗した後にファイルの位置を復元しません。

データの書式設定が競合するため、次のエンコードでこのメソッドを使用することはお勧めしません。

  • UTF-7

  • ISO-2022-JP

  • ISCII

共通 I/O タスクの一覧は、 共通 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.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

こちらもご覧ください