BinaryReader.Read BinaryReader.Read BinaryReader.Read BinaryReader.Read Method

定義

基になるストリームからバイトを読み取り、ストリームの現在位置を進めます。Reads bytes from the underlying stream and advances the current position of the stream.

オーバーロード

Read() Read() Read() Read()

基になるストリームから文字を読み取り、使用した Encoding とストリームから読み取った特定の文字に従ってストリームの現在位置を進めます。Reads characters from the underlying stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream.

Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>)
Read(Span<Char>) Read(Span<Char>) Read(Span<Char>) Read(Span<Char>)
Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)

バイト配列内の指定された位置を開始点として、ストリームから指定されたバイト数を読み取ります。Reads the specified number of bytes from the stream, starting from a specified point in the byte array.

Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32)

文字配列内の指定された位置を開始点として、ストリームから指定された文字数を読み取ります。Reads the specified number of characters from the stream, starting from a specified point in the character array.

Read() Read() Read() Read()

基になるストリームから文字を読み取り、使用した Encoding とストリームから読み取った特定の文字に従ってストリームの現在位置を進めます。Reads characters from the underlying stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream.

public:
 virtual int Read();
public virtual int Read ();
abstract member Read : unit -> int
override this.Read : unit -> int
Public Overridable Function Read () As Integer

戻り値

入力ストリームの次の文字。現在読み取り可能な文字がない場合は -1。The next character from the input stream, or -1 if no characters are currently available.

例外

I/O エラーが発生します。An I/O error occurs.

ストリームは閉じられています。The stream is closed.

次の例は、バッキングストアとしてメモリを使用してデータの読み取りと書き込みを行う方法を示しています。The following example shows how to read and write data using memory as a backing store. この例では、無効なファイルパス文字の一覧をコンソールに表示します。This example displays a list of invalid file path characters to the console. コードはすべての無効なファイルパス文字の一覧を表示しようとしますが、すべての文字が表示可能な文字のセット内に含まれているわけではありません。Although the code tries to display a list of all invalid file path characters, not all of the characters are within the displayable set of characters. 無効な文字の一覧はシステムによって異なる場合があるため、このコードの出力も異なる場合があります。Because the list of invalid characters can vary based on the system, output for this code may also vary.

using namespace System;
using namespace System::IO;
int main()
{
   int i;
   array<Char>^invalidPathChars = Path::InvalidPathChars;
   MemoryStream^ memStream = gcnew MemoryStream;
   BinaryWriter^ binWriter = gcnew BinaryWriter( memStream );
   
   // Write to memory.
   binWriter->Write( "Invalid file path characters are: " );
   for ( i = 0; i < invalidPathChars->Length; i++ )
   {
      binWriter->Write( invalidPathChars[ i ] );

   }
   
   // Create the reader using the same MemoryStream 
   // as used with the writer.
   BinaryReader^ binReader = gcnew BinaryReader( memStream );
   
   // Set Position to the beginning of the stream.
   binReader->BaseStream->Position = 0;
   
   // Read the data from memory and write it to the console.
   Console::Write( binReader->ReadString() );
   array<Char>^memoryData = gcnew array<Char>(memStream->Length - memStream->Position);
   for ( i = 0; i < memoryData->Length; i++ )
   {
      memoryData[ i ] = Convert::ToChar( binReader->Read() );

   }
   Console::WriteLine( memoryData );
}

using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i = 0;
        char[] invalidPathChars = Path.InvalidPathChars;
        MemoryStream memStream = new MemoryStream();
        BinaryWriter binWriter = new BinaryWriter(memStream);

        // Write to memory.
        binWriter.Write("Invalid file path characters are: ");
        for(i = 0; i < invalidPathChars.Length; i++)
        {
            binWriter.Write(invalidPathChars[i]);
        }

        // Create the reader using the same MemoryStream 
        // as used with the writer.
        BinaryReader binReader = new BinaryReader(memStream);

        // Set Position to the beginning of the stream.
        memStream.Position = 0;

        // Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString());
        char[] memoryData = 
            new char[memStream.Length - memStream.Position];
        for(i = 0; i < memoryData.Length; i++)
        {
            memoryData[i] = Convert.ToChar(binReader.Read());
        }
        Console.WriteLine(memoryData);
    }
}
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        Dim i As Integer = 0
        Dim invalidPathChars() As Char = Path.InvalidPathChars
        Dim memStream As new MemoryStream()
        Dim binWriter As New BinaryWriter(memStream)

        ' Write to memory.
        binWriter.Write("Invalid file path characters are: ")
        For i = 0 To invalidPathChars.Length - 1
            binWriter.Write(invalidPathChars(i))
        Next i

        ' Create the reader using the same MemoryStream 
        ' as used with the writer.
        Dim binReader As New BinaryReader(memStream)

        ' Set Position to the beginning of the stream.
        memStream.Position = 0

        ' Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString())
        Dim memoryData( _
            CInt(memStream.Length - memStream.Position) - 1) As Char
        For i = 0 To memoryData.Length - 1
            memoryData(i) = Convert.ToChar(binReader.Read())
        Next i
        Console.WriteLine(memoryData)
    
	End Sub
End Class

注釈

BinaryReaderは、読み取りに失敗した後にファイルの位置を復元しません。BinaryReader does not restore the file position after an unsuccessful read.

共通 I/O タスクの一覧は、 共通 I/O タスク を参照してください。For a list of common I/O tasks, see Common I/O Tasks.

こちらもご覧ください

Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>)

public:
 virtual int Read(Span<System::Byte> buffer);
public virtual int Read (Span<byte> buffer);
abstract member Read : Span<byte> -> int
override this.Read : Span<byte> -> int
Public Overridable Function Read (buffer As Span(Of Byte)) As Integer

パラメーター

buffer
Span<Byte>

戻り値

Read(Span<Char>) Read(Span<Char>) Read(Span<Char>) Read(Span<Char>)

public:
 virtual int Read(Span<char> buffer);
public virtual int Read (Span<char> buffer);
abstract member Read : Span<char> -> int
override this.Read : Span<char> -> int
Public Overridable Function Read (buffer As Span(Of Char)) As Integer

パラメーター

buffer
Span<Char>

戻り値

Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)

バイト配列内の指定された位置を開始点として、ストリームから指定されたバイト数を読み取ります。Reads the specified number of bytes from the stream, starting from a specified point in the byte array.

public:
 virtual int Read(cli::array <System::Byte> ^ buffer, int index, int count);
public virtual int Read (byte[] buffer, int index, int count);
abstract member Read : byte[] * int * int -> int
override this.Read : byte[] * int * int -> int
Public Overridable Function Read (buffer As Byte(), index As Integer, count As Integer) As Integer

パラメーター

buffer
Byte[]

データを読み取るバッファー。The buffer to read data into.

index
Int32 Int32 Int32 Int32

バッファー内の、バッファーへの読み取り開始点。The starting point in the buffer at which to begin reading into the buffer.

count
Int32 Int32 Int32 Int32

読み取るバイト数。The number of bytes to read.

戻り値

buffer に読み取るバイト数。The number of bytes read into buffer. 要求したバイト数分のバイトを読み取れなかった場合、この値は要求したバイト数より小さくなります。ストリームの末尾に到達した場合は 0 になることがあります。This might be less than the number of bytes requested if that many bytes are not available, or it might be zero if the end of the stream is reached.

例外

バッファーの長さから index を引いた値が count 未満です。The buffer length minus index is less than count.

または-or- デコードされた文字の数が count を超えています。The number of decoded characters to read is greater than count. これは、Unicode デコーダーがフォールバック文字またはサロゲート ペアを返す場合に発生することがあります。This can happen if a Unicode decoder returns fallback characters or a surrogate pair.

index または count が負の値です。index or count is negative.

ストリームは閉じられています。The stream is closed.

I/O エラーが発生します。An I/O error occurs.

次の例では、バッキングストアとしてメモリを使用してバイナリデータを書き込む方法を示します。The following example shows how to write binary data by using memory as a backing store. データが正しく書き込まれたかどうかを示すメッセージがコンソールに表示されます。It displays a message to the console that indicates whether the data was written correctly.

using System;
using System.IO;

namespace BinaryRW
{
    class Program
    {
        static void Main(string[] args)
        {
            const int arrayLength = 1000;
            byte[] dataArray = new byte[arrayLength];
            byte[] verifyArray = new byte[arrayLength];

            new Random().NextBytes(dataArray);

            using (BinaryWriter binWriter = new BinaryWriter(new MemoryStream()))
            {
                Console.WriteLine("Writing the data.");
                binWriter.Write(dataArray, 0, arrayLength);

                using (BinaryReader binReader = new BinaryReader(binWriter.BaseStream))
                {
                    binReader.BaseStream.Position = 0;
                    
                    if (binReader.Read(verifyArray, 0, arrayLength) != arrayLength)
                    {
                        Console.WriteLine("Error writing the data.");
                        return;
                    }
                }
            }

            for (int i = 0; i < arrayLength; i++)
            {
                if (verifyArray[i] != dataArray[i])
                {
                    Console.WriteLine("Error writing the data.");
                    return;
                }
            }

            Console.WriteLine("The data was written and verified.");
        }
    }
}
Imports System.IO

Module Module1

    Sub Main()
        Const upperBound As Integer = 1000
        Dim dataArray(upperBound) As Byte
        Dim verifyArray(upperBound) As Byte

        Dim randomGenerator As New Random
        randomGenerator.NextBytes(dataArray)

        Using binWriter As New BinaryWriter(New MemoryStream())
            Console.WriteLine("Writing the data.")
            binWriter.Write(dataArray, 0, dataArray.Length)

            Using binReader As New BinaryReader(binWriter.BaseStream)
                binReader.BaseStream.Position = 0

                If binReader.Read(verifyArray, 0, dataArray.Length) <> dataArray.Length Then
                    Console.WriteLine("Error writing the data.")
                    Return
                End If
            End Using
        End Using

        For i As Integer = 0 To upperBound
            If verifyArray(i) <> dataArray(i) Then
                Console.WriteLine("Error writing the data.")
                Return
            End If
        Next i

        Console.WriteLine("The data was written and verified.")
    End Sub

End Module

この例では、ファイルの内容を読み取り、各バイトの数値を16列形式で表示します。This example reads the contents of a file and displays each byte's numeric value in 16-column format. メソッドがRead 0 バイトを返すと、読み取り中のファイルの末尾が検出されます。The end of the file that is being read is detected when the Read method returns zero bytes.

using System;
using System.IO;
using System.Text;

public class DumpFileSample
{
    private static readonly int CHUNK_SIZE = 1024;
    public static void Main(String[] args)
    {
        if ((args.Length == 0) || !File.Exists(args[0]))
        {
            Console.WriteLine("Please provide an existing file name.");
        }
        else
        {
            using (FileStream fs = new FileStream(args[0], FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader br = new BinaryReader(fs, new ASCIIEncoding()))
                {
                    byte[] chunk;

                    chunk = br.ReadBytes(CHUNK_SIZE);
                    while(chunk.Length > 0)
                    {
                        DumpBytes(chunk, chunk.Length);
                        chunk = br.ReadBytes(CHUNK_SIZE);
                    }
                }
            }
        }
    }

    public static void DumpBytes(byte[] bdata, int len)
    {
        int i;
        int j = 0;
        char dchar;
        // 3 * 16 chars for hex display, 16 chars for text and 8 chars
        // for the 'gutter' int the middle.
        StringBuilder dumptext = new StringBuilder("        ", 16 * 4 + 8);
        for (i = 0; i < len; i++)
        {
            dumptext.Insert(j * 3, String.Format("{0:X2} ", (int)bdata[i]));
            dchar = (char)bdata[i];
            //' replace 'non-printable' chars with a '.'.
            if (Char.IsWhiteSpace(dchar) || Char.IsControl(dchar))
            {
                dchar = '.';
            }
            dumptext.Append(dchar);
            j++;
            if (j == 16)
            {
                Console.WriteLine(dumptext);
                dumptext.Length = 0;
                dumptext.Append("        ");
                j = 0;
            }
        }
        // display the remaining line
        if (j > 0)
        {
            for (i = j; i < 16; i++)
            {
                dumptext.Insert(j * 3, "   ");
            }
            Console.WriteLine(dumptext);
        }
    }
}
Imports System.IO
Imports System.Text

Module Module1
    Private ReadOnly CHUNK_SIZE As Integer = 1024
    Public Sub Main(args() As String)
        If ((args.Length = 0) OrElse Not File.Exists(args(0))) Then
            Console.WriteLine("Please provide an existing file name.")
        Else
            Using fs As FileStream = New FileStream(args(0), FileMode.Open, FileAccess.Read)
                Using br As New BinaryReader(fs, New ASCIIEncoding())
                    Dim chunk(CHUNK_SIZE) As Byte
                    chunk = br.ReadBytes(CHUNK_SIZE)

                    While chunk.Length > 0
                        DumpBytes(chunk, chunk.Length)
                        chunk = br.ReadBytes(CHUNK_SIZE)
                    End While
                End Using
            End Using
        End If
    End Sub

    Public Sub DumpBytes(bdata() As Byte, len As Integer)
        Dim i As Integer
        Dim j As Integer = 0
        Dim dchar As Char
        ' 3 * 16 chars for hex display, 16 chars for text and 8 chars
        ' for the 'gutter' int the middle.
        Dim dumptext As New StringBuilder("        ", 16 * 4 + 8)
        For i = 0 To len - 1
            dumptext.Insert(j * 3, String.Format("{0:X2} ", CType(bdata(i), Integer)))
            dchar = Convert.ToChar(bdata(i))
            ' replace 'non-printable' chars with a '.'.
            If Char.IsWhiteSpace(dchar) Or Char.IsControl(dchar) Then
                dchar = "."
            End If
            dumptext.Append(dchar)
            j += 1
            If j = 16 Then
                Console.WriteLine(dumptext)
                dumptext.Length = 0
                dumptext.Append("        ")
                j = 0
            End If
        Next i
        ' display the remaining line
        If j > 0 Then
            ' add blank hex spots to align the 'gutter'.
            For i = j To 15
                dumptext.Insert(j * 3, "   ")
            Next i
            Console.WriteLine(dumptext)
        End If
    End Sub

End Module

注釈

BinaryReaderでは、読み取り操作が失敗した後、ファイルの位置は復元されません。BinaryReader does not restore the file position after an unsuccessful read operation.

共通 I/O タスクの一覧は、 共通 I/O タスク を参照してください。For a list of common I/O tasks, see Common I/O Tasks.

こちらもご覧ください

Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32) Read(Char[], Int32, Int32)

文字配列内の指定された位置を開始点として、ストリームから指定された文字数を読み取ります。Reads the specified number of characters from the stream, starting from a specified point in the character array.

public:
 virtual int Read(cli::array <char> ^ buffer, int index, int count);
public virtual int Read (char[] buffer, int index, int count);
abstract member Read : char[] * int * int -> int
override this.Read : char[] * int * int -> int
Public Overridable Function Read (buffer As Char(), index As Integer, count As Integer) As Integer

パラメーター

buffer
Char[]

データを読み取るバッファー。The buffer to read data into.

index
Int32 Int32 Int32 Int32

バッファー内の、バッファーへの読み取り開始点。The starting point in the buffer at which to begin reading into the buffer.

count
Int32 Int32 Int32 Int32

読み取る文字の数。The number of characters to read.

戻り値

バッファーに読み取られた合計文字数。The total number of characters read into the buffer. 要求した文字数分の文字を読み取れなかった場合、この値は要求した文字数より小さくなります。また、ストリームの末尾に到達した場合は 0 になることがあります。This might be less than the number of characters requested if that many characters are not currently available, or it might be zero if the end of the stream is reached.

例外

バッファーの長さから index を引いた値が count 未満です。The buffer length minus index is less than count.

- または --or- デコードされた文字の数が count を超えています。The number of decoded characters to read is greater than count. これは、Unicode デコーダーがフォールバック文字またはサロゲート ペアを返す場合に発生することがあります。This can happen if a Unicode decoder returns fallback characters or a surrogate pair.

index または count が負の値です。index or count is negative.

ストリームは閉じられています。The stream is closed.

I/O エラーが発生します。An I/O error occurs.

次の例は、バッキングストアとしてメモリを使用してデータの読み取りと書き込みを行う方法を示しています。The following example shows how to read and write data using memory as a backing store. この例では、無効なファイルパス文字の一覧をコンソールに表示します。This example displays a list of invalid file path characters to the console. コードはすべての無効なファイルパス文字の一覧を表示しようとしますが、すべての文字が表示可能な文字のセット内に含まれているわけではありません。Although the code tries to display a list of all invalid file path characters, not all of the characters are within the displayable set of characters. 無効な文字の一覧はシステムによって異なる場合があるため、このコードの出力も異なる場合があります。Because the list of invalid characters can vary based on the system, output for this code may also vary.

using namespace System;
using namespace System::IO;
int main()
{
   array<Char>^invalidPathChars = Path::InvalidPathChars;
   MemoryStream^ memStream = gcnew MemoryStream;
   BinaryWriter^ binWriter = gcnew BinaryWriter( memStream );
   
   // Write to memory.
   binWriter->Write( "Invalid file path characters are: " );
   binWriter->Write( Path::InvalidPathChars, 0, Path::InvalidPathChars->Length );
   
   // Create the reader using the same MemoryStream 
   // as used with the writer.
   BinaryReader^ binReader = gcnew BinaryReader( memStream );
   
   // Set Position to the beginning of the stream.
   binReader->BaseStream->Position = 0;
   
   // Read the data from memory and write it to the console.
   Console::Write( binReader->ReadString() );
   int arraySize = (int)(memStream->Length - memStream->Position);
   array<Char>^memoryData = gcnew array<Char>(arraySize);
   binReader->Read( memoryData, 0, arraySize );
   Console::WriteLine( memoryData );
}

using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        char[] invalidPathChars = Path.InvalidPathChars;
        MemoryStream memStream = new MemoryStream();
        BinaryWriter binWriter = new BinaryWriter(memStream);

        // Write to memory.
        binWriter.Write("Invalid file path characters are: ");
        binWriter.Write(
            Path.InvalidPathChars, 0, Path.InvalidPathChars.Length);

        // Create the reader using the same MemoryStream 
        // as used with the writer.
        BinaryReader binReader = new BinaryReader(memStream);

        // Set Position to the beginning of the stream.
        memStream.Position = 0;

        // Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString());
        int arraySize = (int)(memStream.Length - memStream.Position);
        char[] memoryData = new char[arraySize];
        binReader.Read(memoryData, 0, arraySize);
        Console.WriteLine(memoryData);
    }
}
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        Dim invalidPathChars() As Char = Path.InvalidPathChars
        Dim memStream As new MemoryStream()
        Dim binWriter As New BinaryWriter(memStream)

        ' Write to memory.
        binWriter.Write("Invalid file path characters are: ")
        binWriter.Write(Path.InvalidPathChars, 0, _
            Path.InvalidPathChars.Length)

        ' Create the reader using the same MemoryStream 
        ' as used with the writer.
        Dim binReader As New BinaryReader(memStream)

        ' Set Position to the beginning of the stream.
        memStream.Position = 0

        ' Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString())
        Dim upperBound As Integer = _
            CInt(memStream.Length - memStream.Position) - 1
        Dim memoryData(upperBound) As Char
        binReader.Read(memoryData, 0, upperBound)
        Console.WriteLine(memoryData)
    
	End Sub
End Class

注釈

BinaryReaderでは、読み取り操作が失敗した後、ファイルの位置は復元されません。BinaryReader does not restore the file position after an unsuccessful read operation.

共通 I/O タスクの一覧は、 共通 I/O タスク を参照してください。For a list of common I/O tasks, see Common I/O Tasks.

こちらもご覧ください

適用対象