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

การใช้ C# BinaryWriter Class

BinaryWriter Class ใน C#

BinaryWriter เขียน Primitive Types (int, double, string, bool, etc.) เป็น Binary Format ลง Stream ใช้ร่วมกับ BinaryReader สำหรับอ่านกลับ

Constructor


new BinaryWriter(Stream output)
new BinaryWriter(Stream output, Encoding encoding)
new BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)

เมธอด Write หลัก

Methodคำอธิบาย
Write(bool)1 Byte
Write(byte)1 Byte
Write(char)2 Bytes (UTF-16)
Write(int/long/float/double/decimal)4/8/4/8/16 Bytes
Write(string)Length-prefixed UTF-8 String
Write(byte[])Byte Array

ตัวอย่าง: เขียนและอ่าน Binary File


using System;
using System.IO;

class Program
{
    static void WriteData()
    {
        using (BinaryWriter writer = new BinaryWriter(File.Open("data.bin", FileMode.Create)))
        {
            writer.Write(37.8);        // double
            writer.Write("Test Data"); // string
            writer.Write(42);          // int
            writer.Write(true);        // bool
        }
        Console.WriteLine("Write Complete");
    }
    
    static void ReadData()
    {
        using (BinaryReader reader = new BinaryReader(File.Open("data.bin", FileMode.Open)))
        {
            double d = reader.ReadDouble();   // 37.8
            string s = reader.ReadString();   // "Test Data"
            int i = reader.ReadInt32();       // 42
            bool b = reader.ReadBoolean();    // true
            
            Console.WriteLine($"Double: {d}, String: {s}, Int: {i}, Bool: {b}");
        }
    }
    
    static void Main()
    {
        WriteData();
        ReadData();
        Console.ReadKey();
    }
}

ผลลัพธ์


Write Complete
Double: 37.8, String: Test Data, Int: 42, Bool: True

ข้อควรระวัง

  • Endianness: BinaryWriter ใช้ Little-Endian เสมอ (อาจไม่เข้ากับ Big-Endian Systems)
  • String Format: Length-prefixed (7-bit encoded int) + UTF-8 Bytes
  • Versioning: ไม่มี Schema - เปลี่ยนโครงสร้างอ่านไม่ได้
  • Security: BinaryFormatter ไม่ปลอดภัย (Deprecated) - BinaryWriter Manual ปลอดภัยกว่า

เมื่อไหร่ใช้ BinaryWriter

  • High-performance Binary Serialization
  • Custom File Formats
  • Network Protocols (Binary)
  • Interop กับ Native Code