BinaryReader.Read 메서드

정의

내부 스트림에서 바이트를 읽고 스트림의 현재 위치를 앞으로 이동합니다.

오버로드

Read()

내부 스트림에서 문자를 읽고 사용된 Encoding과 스트림에서 읽어오는 특정 문자의 길이만큼 스트림의 현재 위치를 앞으로 이동합니다.

Read(Span<Byte>)

현재 스트림에서 바이트 시퀀스를 읽고 읽은 바이트 수만큼 스트림에서 위치를 앞으로 이동합니다.

Read(Span<Char>)

현재 스트림에서 제공된 버퍼의 길이와 동일한 문자 수만큼 읽어 제공된 버퍼에 쓰고 사용된 Encoding과 스트림에서 읽어 오는 특정 문자의 길이만큼 현재 위치를 앞으로 이동합니다.

Read(Byte[], Int32, Int32)

바이트 배열의 지정된 지점부터 스트림에서 지정된 바이트 수만큼 읽습니다.

Read(Char[], Int32, Int32)

문자 배열의 지정된 지점부터 스트림에서 지정된 문자 수만큼 읽습니다.

Read()

내부 스트림에서 문자를 읽고 사용된 Encoding과 스트림에서 읽어오는 특정 문자의 길이만큼 스트림의 현재 위치를 앞으로 이동합니다.

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

반환

Int32

입력 스트림의 다음 문자를 반환하고 현재 사용할 수 있는 문자가 없을 경우 -1을 반환합니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

예제

다음 예제에서는 메모리를 백업 저장소로 사용하여 데이터를 읽고 쓰는 방법을 보여줍니다. 다음은 콘솔에 잘못된 파일 경로 문자 목록을 표시하는 예제입니다. 코드에서 모든 잘못된 파일 경로 문자 목록을 표시하려고 하지만 모든 문자가 표시 가능한 문자 집합 내에 있는 것은 아닙니다. 잘못된 문자 목록은 시스템에 따라 달라질 수 있으므로 이 코드의 출력도 달라질 수 있습니다.

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);
    }
}
open System
open System.IO

let invalidPathChars = Path.GetInvalidPathChars()
let memStream = new MemoryStream()
let binWriter = new BinaryWriter(memStream)

// Write to memory.
printf "Invalid file path characters are: "
for i = 0 to invalidPathChars.Length - 1 do
    binWriter.Write invalidPathChars[i]

// Create the reader using the same MemoryStream
// as used with the writer.
let 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.
printf $"{binReader.ReadString()}"
let memoryData =
    [| for _ = 0L to memStream.Length - memStream.Position - 1L do
        Convert.ToChar(binReader.Read()) |]
printfn $"{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 는 실패한 읽기 후에 파일 위치를 복원하지 않습니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

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>

메모리 영역입니다. 이 메서드가 반환될 때 이 영역의 내용은 현재 소스에서 읽은 바이트로 대체됩니다.

반환

Int32

버퍼로 읽어온 총 바이트 수입니다. 많은 바이트가 현재 사용 가능하지 않은 경우 버퍼에 할당된 바이트 수보다 작을 수 있으며 스트림의 끝에 도달하면 0이 됩니다.

예외

스트림이 닫혔습니다.

I/O 오류가 발생했습니다.

적용 대상

Read(Span<Char>)

현재 스트림에서 제공된 버퍼의 길이와 동일한 문자 수만큼 읽어 제공된 버퍼에 쓰고 사용된 Encoding과 스트림에서 읽어 오는 특정 문자의 길이만큼 현재 위치를 앞으로 이동합니다.

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>

문자 범위입니다. 이 메서드가 반환될 때 이 영역의 내용은 현재 소스에서 읽은 문자로 대체됩니다.

반환

Int32

버퍼로 읽어온 총 문자 수입니다. 이 문자 수는 문자가 현재 충분하지 않은 경우 요청된 문자 수보다 작을 수 있으며 스트림의 끝에 도달하면 0이 됩니다.

예외

스트림이 닫혔습니다.

I/O 오류가 발생했습니다.

적용 대상

Read(Byte[], Int32, Int32)

바이트 배열의 지정된 지점부터 스트림에서 지정된 바이트 수만큼 읽습니다.

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[]

데이터를 읽어올 버퍼입니다.

index
Int32

버퍼로 읽어오기를 시작할 버퍼의 시작 위치입니다.

count
Int32

읽을 바이트 수입니다.

반환

Int32

buffer로 읽어 온 바이트 수입니다. 이 바이트 수는 바이트가 충분하지 않은 경우 요청된 바이트 수보다 작을 수 있으며 스트림의 끝에 도달하면 0이 됩니다.

예외

버퍼 길이에서 index를 빼면 count보다 작습니다.

또는 읽을 수 있도록 디코딩된 문자의 수는 count보다 큽니다. 유니코드 디코더가 대체 문자 또는 서로게이트 쌍을 반환하는 경우 이 문제가 발생할 수 있습니다.

buffer이(가) null인 경우

index 또는 count가 음수입니다.

스트림이 닫혔습니다.

I/O 오류가 발생했습니다.

예제

다음 예제에서는 메모리를 백업 저장소로 사용하여 이진 데이터를 작성하는 방법을 보여 있습니다. 데이터가 올바르게 작성되었는지 여부를 나타내는 메시지를 콘솔에 표시합니다.

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.");
        }
    }
}
open System
open System.IO

let arrayLength = 1000
let dataArray = Array.zeroCreate<byte> arrayLength
let verifyArray = Array.zeroCreate<byte> arrayLength

Random().NextBytes dataArray

do
    use binWriter = new BinaryWriter(new MemoryStream())
    printfn "Writing the data."
    binWriter.Write(dataArray, 0, arrayLength)

    use binReader = new BinaryReader(binWriter.BaseStream)
    binReader.BaseStream.Position <- 0

    if binReader.Read(verifyArray, 0, arrayLength) <> arrayLength then
        printfn "Error writing the data."
    else
        for i = 0 to arrayLength - 1 do
            if verifyArray[i] <> dataArray[i] then
                printfn "Error writing the data."
            else
                printfn "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열 형식으로 표시합니다. 읽는 파일의 끝은 메서드가 0바이트를 반환할 Read 때 검색됩니다.

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);
        }
    }
}
open System
open System.IO
open System.Text

let CHUNK_SIZE = 1024

let dumpBytes (bdata: byte[]) len =
    let mutable j = 0
    // 3 * 16 chars for hex display, 16 chars for text and 8 chars
    // for the 'gutter' int the middle.
    let dumptext = StringBuilder("        ", 16 * 4 + 8)
    for i = 0 to len - 1 do
        dumptext.Insert(j * 3, $"{int bdata[i]:X2} ") |> ignore
        let dchar = char bdata[i]
        //' replace 'non-printable' chars with a '.'.
        let dchar = 
            if Char.IsWhiteSpace dchar || Char.IsControl dchar then
                '.'
            else 
                dchar
        dumptext.Append dchar |> ignore
        j <- j + 1
        if j = 16 then
            printfn $"{dumptext}"
            dumptext.Length <- 0
            dumptext.Append "        " |> ignore
            j <- 0
    // display the remaining line
    if j > 0 then
        for i = j to 15 do
            dumptext.Insert(j * 3, "   ") |> ignore
        printfn $"{dumptext}"

[<EntryPoint>]
let main args =
    if args.Length = 0 || File.Exists args[0] |> not then
        printfn "Please provide an existing file name."
    else
        use fs = new FileStream(args[0], FileMode.Open, FileAccess.Read)
        use br = new BinaryReader(fs, ASCIIEncoding())
        
        let mutable chunk = br.ReadBytes CHUNK_SIZE
        while chunk.Length > 0 do
            dumpBytes chunk chunk.Length
            chunk <- br.ReadBytes CHUNK_SIZE
    0
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 는 실패한 읽기 작업 후에 파일 위치를 복원하지 않습니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Read(Char[], Int32, Int32)

문자 배열의 지정된 지점부터 스트림에서 지정된 문자 수만큼 읽습니다.

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[]

데이터를 읽어올 버퍼입니다.

index
Int32

버퍼로 읽어오기를 시작할 버퍼의 시작 위치입니다.

count
Int32

읽을 문자 수입니다.

반환

Int32

버퍼로 읽어온 총 문자 수입니다. 이 문자 수는 문자가 현재 충분하지 않은 경우 요청된 문자 수보다 작을 수 있으며 스트림의 끝에 도달하면 0이 됩니다.

예외

버퍼 길이에서 index를 빼면 count보다 작습니다.

또는 읽을 수 있도록 디코딩된 문자의 수는 count보다 큽니다. 유니코드 디코더가 대체 문자 또는 서로게이트 쌍을 반환하는 경우 이 문제가 발생할 수 있습니다.

buffer이(가) null인 경우

index 또는 count가 음수입니다.

스트림이 닫혔습니다.

I/O 오류가 발생했습니다.

예제

다음 예제에서는 메모리를 백업 저장소로 사용하여 데이터를 읽고 쓰는 방법을 보여줍니다. 다음은 콘솔에 잘못된 파일 경로 문자 목록을 표시하는 예제입니다. 코드에서 모든 잘못된 파일 경로 문자 목록을 표시하려고 하지만 모든 문자가 표시 가능한 문자 집합 내에 있는 것은 아닙니다. 잘못된 문자 목록은 시스템에 따라 달라질 수 있으므로 이 코드의 출력도 달라질 수 있습니다.

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);
    }
}
open System.IO

let invalidPathChars = Path.GetInvalidPathChars()
let memStream = new MemoryStream()
let binWriter = new BinaryWriter(memStream)

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

// Create the reader using the same MemoryStream
// as used with the writer.
let 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.
printf $"{binReader.ReadString()}"
let arraySize = memStream.Length - memStream.Position |> int
let memoryData = Array.zeroCreate<char> arraySize
binReader.Read(memoryData, 0, arraySize) |> ignore
printfn $"{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 는 실패한 읽기 작업 후에 파일 위치를 복원하지 않습니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상