Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# 이진 직렬화와 역직렬화 완벽 가이드: 개념부터 구현 방법까지

객체(Object)를 사람이 직접 읽을 수 없는 이진(binary) 형식으로 변환하는 과정을 이진 직렬화(Binary Serialization)라고 합니다. 반대로, 저장된 이진 데이터를 다시 원래 객체 형태로 복원하는 과정은 역직렬화(Deserialization)라고 부릅니다.

C#에서 이진 직렬화를 구현하려면 System.Runtime.Serialization.Formatters.Binary 네임스페이스를 사용해야 합니다. 구체적인 절차는 BinaryFormatter 클래스의 인스턴스를 생성한 뒤, 클래스 내부에 정의된 Serialize 메서드를 호출하는 것입니다.

1. 객체를 이진 형식으로 직렬화하기

직렬화 대상이 되는 클래스에는 반드시 [Serializable] 특성(Attribute)을 지정해야 합니다. 아래 예제는 Demo 객체를 파일로 직렬화하는 전체 코드입니다.

// 객체를 이진 형식으로 직렬화
[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();
FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fileStream, sample);
Console.ReadKey();
}
}

출력 결과

AConsoleApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
ConsoleApp.Demo<ApplicationName>k__BackingField-<ApplicationId>k__BackingField
Binary Serialize

실행 결과에서 확인할 수 있듯이, 직렬화된 파일은 사람이 읽기 어려운 이진 데이터 형태로 디스크에 저장됩니다.

2. 이진 데이터를 객체로 역직렬화하기

역직렬화는 Deserialize 메서드를 사용하며, 반환되는 값을 원래 타입으로 명시적으로 캐스팅(casting)해야 한다는 점에 유의하세요.

// 이진 데이터를 다시 객체로 변환
[Serializable]
public class Demo {
public string ApplicationName { get; set; }
public int ApplicationId { get; set; }
}
class Program {
static void Main() {
FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat", FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
Demo deserializedSampledemo = (Demo)formatter.Deserialize(fileStream);
Console.WriteLine($"ApplicationName {deserializedSampledemo.ApplicationName} --- ApplicationId {deserializedSampledemo.ApplicationId}");
Console.ReadKey();
}
}

출력 결과

ApplicationName Binary Serialize --- ApplicationId 1001

역직렬화가 성공적으로 완료되면, 파일에 저장했던 객체의 속성 값들이 그대로 복원되어 출력되는 것을 확인할 수 있습니다.

참고: BinaryFormatter 보안 주의사항

BinaryFormatter는 역직렬화 과정에서 신뢰할 수 없는 데이터가 주입될 경우 임의 코드 실행으로 이어질 수 있는 보안 취약점이 알려져 있습니다. 이로 인해 .NET 5 이상에서는 사용이 권장되지 않으며, 최신 버전의 .NET에서는 기본적으로 오류가 발생하도록 설정되어 있습니다. 따라서 새로운 프로젝트에서는 System.Text.Json을 활용한 JSON 직렬화나 MessagePack과 같은 안전한 대체 기술을 사용하는 것이 좋습니다.