using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace EX14_FILEIO_Serialization
{
[Serializable]
public class Score {
public string Name { get; set; }
public int HighScore { get; set; }
}
class MainClass
{
private const string FILE_NAME = @"Score.dat";
private static List<Score> scores;
private static void InitScoreList()
{
scores = new List<Score> ();
scores.Add (new Score () { Name = "홍길동", HighScore = 3000 });
scores.Add (new Score () { Name = "임꺽정", HighScore = 2500 });
scores.Add (new Score () { Name = "장길산", HighScore = 2000 });
scores.Add (new Score () { Name = "설인범", HighScore = 1500 });
scores.Add (new Score () { Name = "도둑넘", HighScore = 1000 });
}
public static void Serialize()
{
FileStream fs = new FileStream(FILE_NAME, FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, scores);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
public static void Deserialize()
{
scores = null;
// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream(FILE_NAME, FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
scores = (List<Score>) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
foreach (Score s in scores) {
Console.WriteLine("{0} : {1}", s.Name, s.HighScore);
}
}
public static void Main (string[] args)
{
InitScoreList();
Serialize ();
Deserialize ();
}
}
}