C# 바이너리리더

WBOY
풀어 주다: 2024-09-03 15:22:40
원래의
488명이 탐색했습니다.

C#에서 BinaryReader는 바이너리 데이터를 처리하는 데 사용되는 클래스입니다. System.IO 네임스페이스 아래에 있습니다. BinaryReader는 특정 인코딩 스트림에서 기본 데이터 유형을 이진 값으로 읽는 데 사용됩니다. BinaryReader는 Stream 객체와 함께 작동합니다. 즉, BinaryReader의 객체를 생성하려면 생성자에 Stream 객체를 전달해야 합니다. BinaryReader 클래스에는 이진 데이터 작업을 위한 세 개의 오버로드된 생성자가 있습니다. 기본적으로 BinaryReader는 객체를 생성하는 동안 다른 문자 인코딩을 지정할 때까지 UTF-8 인코딩을 사용하여 데이터를 읽습니다.

설명이 포함된 구문

다음과 같이 세 가지 방법으로 BinaryReader의 개체를 생성할 수 있습니다.

BinaryReader binary_reader = new BinaryReader(inputStream);
로그인 후 복사

위 명령문은 UTF-8 인코딩을 사용하여 지정된 스트림(inputStream)을 기반으로 BinaryReader의 새 인스턴스를 초기화합니다.

BinaryReader binary_reader = new BinaryReader(inputStream, encoding);
로그인 후 복사

이 문은 지정된 스트림(inputStream)과 인코딩에 의해 지정된 인코딩을 기반으로 BinaryReader의 새 인스턴스를 초기화합니다.

BinaryReader binary_reader = new BinaryReader(inputStream, encoding, true);
로그인 후 복사
로그인 후 복사

이 문은 BinaryReader 개체가 삭제된 후 사용자가 스트림을 열어두기를 원하는지 여부를 지정하는 데 사용되는 부울 유형의 추가 매개 변수를 사용하여 위의 두 문과 동일하게 작동합니다. 스트림을 열린 상태로 두려면 이 매개변수가 'true'여야 하며, 그렇지 않으면 'false'여야 합니다.

이 세 가지 방법 외에도 다음 명령문을 사용하여 BinaryReader를 생성할 수도 있습니다.

using(BinaryReader binary_reader = new BinaryReader(File.Open(file_path, FileMode.Open)))
{
//user code
}
로그인 후 복사

위 구문에서 File.Open() 메서드는 FileStream의 객체를 반환하므로 BinaryReader의 객체를 생성하는 데 도움이 됩니다.

'using' 블록 내부에 객체를 생성하는 이점은 객체 작업이 완료되고 더 이상 필요하지 않을 때 객체가 보유한 메모리를 해제한다는 것입니다.

C#에서 BinaryReader는 어떻게 작동하나요?

BinaryReader는 바이너리 정보를 읽는 데 사용됩니다. 즉, 바이너리 파일에 저장된 데이터를 읽는 데 사용됩니다. 바이너리 파일은 기계가 쉽게 이해할 수 있는 방식으로 데이터를 저장하지만 인간이 그러한 데이터를 이해하는 것은 매우 어렵습니다. 이러한 데이터를 이해하는 데 도움을 주기 위해 BinaryReader가 사용됩니다. BinaryReader를 사용하려면 먼저 코드에서 System.IO 네임스페이스를 가져와야 합니다. 그런 다음 'new' 연산자를 사용하고 BinaryReader 생성자 내에서 Stream 객체를 우회하여 BinaryReader의 인스턴스를 생성해야 합니다.

BinaryReader의 인스턴스를 생성하는 동안 읽을 스트림을 제공한 다음 인코딩을 지정하지 않으면 선택적으로 사용할 문자 인코딩을 지정할 수 있습니다. 기본적으로 UTF-8 인코딩이 사용됩니다. 이와 함께 아래 명령문과 같이 BinaryReader 객체가 삭제된 후 스트림을 열 것인지 선택적으로 지정할 수 있습니다.

BinaryReader binary_reader = new BinaryReader(inputStream, encoding, true);
로그인 후 복사
로그인 후 복사

그런 다음 다양한 데이터 유형에 대해 제공되는 BinaryReader의 다양한 Read() 메서드를 사용하여 파일에서 데이터를 읽을 수 있습니다.

BinaryReader에는 다양한 데이터 유형을 지원하는 많은 Read() 메서드가 있으며 스트림에서 기본 데이터 유형을 읽는 데 사용됩니다. 예를 들어 BinaryReader의 ReadString() 메서드는 다음 바이트를 문자열 값으로 읽는 데 사용되며 스트림의 현재 위치를 1바이트씩 앞으로 이동시킵니다.

다음 표의 다양한 데이터 유형에 대한 BinaryReader의 Read() 메서드:

Method Description
Read() It is used to read characters from an underlying stream and it also advances the current position of the stream according to the Encoding used and the specific character being read from the stream.
ReadBoolean() It is used to read the Boolean value from the stream and it also advances the current position of the stream by one byte.
ReadByte() It is used to read the next byte from the current stream and it also advances the current position of the stream by one byte.
ReadChar() It is used to read the next character from the current stream and it also advances the current position of the stream according to the Encoding used and the specific character being read from the stream.
ReadDecimal() It is used to read the decimal value from the current stream and it also advances the current position of the stream by sixteen bytes.
ReadDouble() It is used to read an 8-byte floating-point value from the current stream and advances the current position of the stream by eight bytes.
ReadInt32() It is used to read a 4-byte signed integer from the current stream and also it advances the current position of the stream by four bytes.
ReadString() It is used to read a string from the current stream.

Example of C# Binaryreader

Example of creating a file using BinaryWriter and reading it using BInaryReader.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp4
{
public class Program
{
string filePath = "E:\\Content\\binaryFile.dat";
public void WriteFile()
{
try
{
//checking if the file already exists
if (File.Exists(filePath))
{
File.Delete(filePath);
}
FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.ReadWrite);
//creating binary file using BinaryWriter
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write("This is string");
writer.Write(100.53);
writer.Write(true);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void ReadFile()
{
try
{
//creating an object of Stream
FileStream stream = new FileStream(filePath, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
//creating BinaryReader using Stream object
using (BinaryReader reader = new BinaryReader(stream))
{
//reading data using Read() methods of different data types
Console.WriteLine("String Value : " + reader.ReadString());
Console.WriteLine("Double Value : " + reader.ReadDouble());
Console.WriteLine("Boolean Value : " + reader.ReadBoolean());
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public class BinaryReaderDemo
{
static void Main(string[] args)
{
Program obj = new Program();
obj.WriteFile();
obj.ReadFile();
Console.ReadKey();
}
}
}
로그인 후 복사

Output:

C# 바이너리리더

Conclusion

BinaryReader is used to read primitive data types as binary values in a specific encoding stream. If not defined explicitly, by default BinaryReader uses UTF-8 encoding to read data. Stream object needs to be passed inside the constructor of BinaryReader in order to create its instance.

위 내용은 C# 바이너리리더의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!