Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การใช้ C# BinaryReader Class

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 หลัก

MethodReturn TypeBytes Read
ReadBoolean()bool1
ReadByte()byte1
ReadChar()char2
ReadInt32()int4
ReadDouble()double8
ReadString()stringVariable (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

ข้อควรระวังสำคัญ

  1. ลำดับการอ่านต้องตรงกับการเขียน (ReadDouble แล้ว ReadString)
  2. End of Stream: อ่านเกิน → EndOfStreamException
  3. Encoding: String ใช้ UTF-8 Length-prefixed (7-bit encoded int)
  4. 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
}