먼저, Serializable을 이용하여 직렬화 구조체를 만든다.


1
2
3
4
5
6
[Serializable()]
public struct COMBO_LIST
{
    public int a;
    public int b;
}
cs

나는 이런식으로 만들었다.


데이터를 저장하는 부분의 소스


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
private void button1_Click(object sender, EventArgs e)
{
    List<COMBO_LIST> list = new List<COMBO_LIST>();
    COMBO_LIST combolist = new COMBO_LIST();
    combolist.a = 1;
    combolist.b = 2;
    list.Add(combolist);
    combolist.a = 3;
    combolist.b = 4;
    list.Add(combolist);
 
    FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
 
    BinaryFormatter formatter = new BinaryFormatter();
    try
    {
        formatter.Serialize(fs, list);
    }
    catch
    {
        Console.WriteLine("실패!!!!");
        throw;
    }
    finally
    {
        fs.Close();
    }
}
cs

파일을 열어 새로운 저장공간에 저장하는 부분의 소스

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
31
private void button2_Click(object sender, EventArgs e)
{
    List<COMBO_LIST> list = new List<COMBO_LIST>();
    COMBO_LIST combolist = new COMBO_LIST();
 
    FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
    try
    {
        BinaryFormatter formatter = new BinaryFormatter();
        list = (List<COMBO_LIST>)formatter.Deserialize(fs);
    }
    catch
    {
        Console.WriteLine("실패!!!!!!!열기");
        throw;
    }
    finally
    {
        fs.Close();
    }
 
    int cnt = list.Count;
    for (int i = 0; i < cnt; i++)
    {
        //데이터 차례로 담기.
        Console.WriteLine("{0} and {1}", list.ElementAt(i).a, list.ElementAt(i).b);
    }
}
 
//결과 : 1 and 2
//       3 and 4
cs


참고사이트 : http://thismoments.tistory.com/58

http://honestgame.tistory.com/37

+ Recent posts