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

Binary Serialization และ Deserialization ใน C# คืออะไร และวิธีทำ

Binary Serialization คืออะไร?

การแปลง Object เป็นรูปแบบ Binary (Byte Array) ที่ มนุษย์อ่านไม่ได้ เพื่อบันทึกลงไฟล์ หรือส่งผ่าน Network

Deserialization คืออะไร?

การแปลง Binary Data กลับเป็น Object เดิม (Human Readable)

Namespace และ Class ที่ใช้

  • Namespace: System.Runtime.Serialization.Formatters.Binary
  • Class หลัก: BinaryFormatter
  • Attribute: [Serializable] ต้องวางบน Class

ตัวอย่าง Serialize (Object → Binary)

[Serializable]
public class Demo
{
    public string ApplicationName { get; set; } = "Binary Serialize";
    public int ApplicationId { get; set; } = 1001;
}

class Program
{
    static void Main()
    {
        Demo sample = new Demo();
        
        using (FileStream fs = new FileStream(@"C:\Temp\Questions.dat", FileMode.Create))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, sample);
        }
        
        Console.WriteLine("Serialized successfully!");
        Console.ReadKey();
    }
}

ตัวอย่าง Deserialize (Binary → Object)

[Serializable]
public class Demo
{
    public string ApplicationName { get; set; }
    public int ApplicationId { get; set; }
}

class Program
{
    static void Main()
    {
        using (FileStream fs = new FileStream(@"C:\Temp\Questions.dat", FileMode.Open))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            Demo deserialized = (Demo)formatter.Deserialize(fs);
            
            Console.WriteLine($"ApplicationName: {deserialized.ApplicationName}");
            Console.WriteLine($"ApplicationId: {deserialized.ApplicationId}");
        }
        Console.ReadKey();
    }
}

Output

ApplicationName: Binary Serialize
ApplicationId: 1001

⚠️ ข้อควรระวัง (Important)

BinaryFormatter ไม่ปลอดภัย (Insecure) และถูก Mark Obsolete แล้วใน .NET 5+
Microsoft แนะนำให้ใช้ Alternative แทน:
  • System.Text.Json - JSON Serializer (เร็ว, ปลอดภัย, มาตรฐาน)
  • MessagePack - Binary Format ที่มีมาตรฐาน เล็กกว่า JSON
  • Protobuf (Google.Protobuf) - Binary แบบ Schema-based
  • XmlSerializer - ถ้าต้องการ XML

ตัวอย่างใช้ System.Text.Json (แนะนำ)

using System.Text.Json;

// Serialize
string json = JsonSerializer.Serialize(sample);
File.WriteAllText("data.json", json);

// Deserialize
string json = File.ReadAllText("data.json");
Demo obj = JsonSerializer.Deserialize<Demo>(json);