[c#] 직렬화와 압축

이번에는 C#에서의 직렬화와 압축에 대해 알아보겠습니다. 직렬화는 객체를 데이터 스트림으로 변환하는 프로세스이고, 압축은 데이터의 용량을 줄여줍니다. 이 두 기술을 함께 사용하면, 보다 효율적으로 데이터를 저장하고 전송할 수 있습니다.

직렬화

직렬화는 객체를 데이터 스트림으로 변환하여 파일로 저장하거나 네트워크를 통해 전송할 수 있도록 합니다. C#에서는 BinaryFormatterJsonSerializer 등을 사용하여 직렬화할 수 있습니다. 이를 통해 객체의 상태를 저장하고 나중에 복원할 수 있습니다.

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

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

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

        BinaryFormatter formatter = new BinaryFormatter();
        using (FileStream stream = new FileStream("person.bin", FileMode.Create))
        {
            formatter.Serialize(stream, person);
        }
    }
}

압축

압축은 데이터의 용량을 줄여주는 프로세스로, 보통 파일을 더 효율적으로 저장하거나 빠르게 전송하기 위해 사용됩니다. C#에서는 System.IO.Compression 네임스페이스를 사용하여 데이터를 압축할 수 있습니다.

using System;
using System.IO;
using System.IO.Compression;

class Program
{
    static void Main()
    {
        byte[] data = File.ReadAllBytes("input.txt");

        using (FileStream compressed = new FileStream("compressed.gz", FileMode.Create))
        {
            using (GZipStream gzip = new GZipStream(compressed, CompressionMode.Compress))
            {
                gzip.Write(data, 0, data.Length);
            }
        }
    }
}

직렬화와 압축 함께 사용하기

직렬화된 데이터를 먼저 압축한 뒤에 저장하거나 전송하는 것이 일반적입니다. 이를 통해 데이터를 보다 효율적으로 저장하고 전송할 수 있습니다.

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

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

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person { Name = "Bob", Age = 25 };

        using (MemoryStream ms = new MemoryStream())
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, person);

            byte[] serializedData = ms.ToArray();

            using (FileStream file = new FileStream("person.bin.gz", FileMode.Create))
            {
                using (GZipStream gzip = new GZipStream(file, CompressionMode.Compress))
                {
                    gzip.Write(serializedData, 0, serializedData.Length);
                }
            }
        }
    }
}

이제 직렬화와 압축을 함께 사용하여 데이터를 효율적으로 다루는 방법에 대해 알아보았습니다.

참고 자료

이상으로 C#에서의 직렬화와 압축에 대해 알아보았습니다.