티스토리 뷰

Code/C#

BinaryFormatter.Serialize 사용법

Hide Code 2007. 12. 12. 21:10
BinaryFormatter.Serialize 와 BinaryFormatter.Deserialize 를 사용한 예제입니다.

아래 예제를 보면 [Serializable] Attribute를 사용한 Name 클래스만 Serialize & Deserialize 한 것을 알 수 있습니다.

이 예제는 사실 BinaryFormatter.Serialize & BinaryFormatter.Deserialize 의 버그 여부를 조사하기 위해서 만들었습니다.

Serialize 후 일부 데이터를 변경하고, 다시 Deserialize 했을 때, 혹시 버그가 있나 검사해봤는데, 정상이었습니다.

BinaryFormatter.Serialize & BinaryFormatter.Deserialize 는 generic static method 로 만들어서 사용했습니다.



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

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            Human boy = new Human();
            boy.name.first = "John";
            boy.name.last = "Dow";
            boy.body.height = 180;
            boy.body.weight = 75;

            Console.WriteLine("{0} {1}", boy.name.first, boy.name.last);
            Console.WriteLine("{0} {1}", boy.body.height, boy.body.weight);

            Serializer.Export<Name>("Sample.dat", boy.name);

            boy.body.height = 160;
            boy.body.weight = 60;
           
            boy.name = Serializer.Import<Name>("Sample.dat");

            Console.WriteLine("{0} {1}", boy.name.first, boy.name.last);
            Console.WriteLine("{0} {1}", boy.body.height, boy.body.weight);
        }
    }

    class Human
    {
        public Name name = new Name();
        public Body body = new Body();
    }

    [Serializable]
    class Name
    {
        public string first;
        public string last;
    }

    class Body
    {
        public int height;
        public int weight;
    }

    class Serializer
    {
        public static void Export<T>(string otherFile, T otherT)
        {
            using (Stream s = File.Open(otherFile, FileMode.Create))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(s, otherT);
            }
        }

        public static T Import<T>(string otherFile)
        {
            using (Stream s = File.Open(otherFile, FileMode.Open))
            {
                BinaryFormatter bf = new BinaryFormatter();
                object o = bf.Deserialize(s);
                T t = (T)o;
                return t;
            }
        }
    }
}


실행 결과 화면은 아래와 같습니다.

정상적인 결과입니다.


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함