[c#] C# Binary 직렬화

C#에서는 객체를 바이너리 형식으로 직렬화하고 역직렬화하는 기능을 제공합니다. BinaryFormatter 클래스를 사용하여 직렬화를 수행하고, MemoryStream 클래스를 사용하여 이진 데이터를 읽고 쓸 수 있습니다.

직렬화

직렬화를 수행하기 위해서는 다음 단계를 따릅니다.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Person
{
    public string Name;
    public int Age;
}

public class Program
{
    public static void Main()
    {
        Person person = new Person { Name = "John", Age = 30 };

        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream memoryStream = new MemoryStream();

        formatter.Serialize(memoryStream, person);
        
        byte[] binaryData = memoryStream.ToArray();
        
        // binaryData를 파일에 쓸 수도 있음
    }
}

위의 예제 코드에서는 Person 클래스를 직렬화하고 MemoryStream 및 BinaryFormatter를 사용하여 이진 데이터로 변환합니다.

역직렬화

이진 데이터를 객체로 역직렬화하려면 다음과 같이합니다.

public static void Main()
{
    byte[] binaryData = ReadBinaryDataFromFileOrOtherSource(); // 이진 데이터를 읽어온다고 가정
    
    BinaryFormatter formatter = new BinaryFormatter();
    MemoryStream memoryStream = new MemoryStream(binaryData);
    
    Person deserializedPerson = (Person)formatter.Deserialize(memoryStream);
    
    Console.WriteLine(deserializedPerson.Name);
    Console.WriteLine(deserializedPerson.Age);
}

이진 데이터를 읽어와 MemoryStream에서 역직렬화를 수행하면 해당 데이터를 객체로 다시 변환할 수 있습니다.

주의사항

C#에서 제공하는 BinaryFormatter를 사용하여 이진 직렬화 및 역직렬화를 수행하는 방법에 대해 알아보았습니다. 이러한 기능을 사용하여 객체를 이진 형식으로 저장하고 읽을 수 있습니다.

MS Docs - BinaryFormatter

MS Docs - MemoryStream

MS Docs - Serialization