BinaryReader Class ใน C#
BinaryReader อ่าน Primitive Types จาก Stream แบบ Binary จำเป็นต้องรู้ลำดับและชนิดข้อมูลที่เขียนไว้ (Paired กับ BinaryWriter)
Constructor
new BinaryReader(Stream input)
new BinaryReader(Stream input, Encoding encoding)
new BinaryReader(Stream input, Encoding encoding, bool leaveOpen)
เมธอด Read หลัก
| Method | Return Type | Bytes Read |
|---|---|---|
ReadBoolean() | bool | 1 |
ReadByte() | byte | 1 |
ReadChar() | char | 2 |
ReadInt32() | int | 4 |
ReadDouble() | double | 8 |
ReadString() | string | Variable (Length-prefixed) |
ReadBytes(count) | byte[] | count |
ตัวอย่าง: อ่านไฟล์ที่ BinaryWriter เขียน
using System;
using System.IO;
class Program
{
static void WriteData()
{
using (BinaryWriter w = new BinaryWriter(File.Open("data.bin", FileMode.Create)))
{
w.Write(25.9); // double
w.Write("DEMO DATA"); // string
}
}
static void ReadData()
{
using (BinaryReader r = new BinaryReader(File.Open("data.bin", FileMode.Open)))
{
double d = r.ReadDouble(); // ต้องเรียกตามลำดับที่เขียน!
string s = r.ReadString();
Console.WriteLine($"Value: {d}");
Console.WriteLine($"Value: {s}");
}
}
static void Main(string[] args)
{
WriteData();
ReadData();
Console.ReadKey();
}
}
ผลลัพธ์
Value: 25.9
Value: DEMO DATA
ข้อควรระวังสำคัญ
- ลำดับการอ่านต้องตรงกับการเขียน (ReadDouble แล้ว ReadString)
- End of Stream: อ่านเกิน →
EndOfStreamException - Encoding: String ใช้ UTF-8 Length-prefixed (7-bit encoded int)
- Position: ใช้
BaseStream.Position/Seekควบคุมตำแหน่ง
PeekChar (ดูตัวถัดไปไม่ Consume)
int peek = reader.PeekChar(); // -1 ถ้าจบ Stream
if (peek != -1)
{
char c = reader.ReadChar();
}
การใช้งานกับ MemoryStream
byte[] data = File.ReadAllBytes("file.bin");
using (MemoryStream ms = new MemoryStream(data))
using (BinaryReader br = new BinaryReader(ms))
{
// Read from memory - fast, no file I/O
}