持久化一个对象
1.对象与文件之间序列化/反序列化
public static void SerializeToFile<T>(T obj,string dataFile) { using (FileStream fileStram = File.Create(dataFile)) { BinaryFormatter binSerializer = new BinaryFormatter(); binSerializer.Serialize(fileStram, obj); } } public static T DeserializeFromFile<T>(string dataFile) { T obj = default(T); using (FileStream fileStream = File.OpenRead(dataFile)) { BinaryFormatter binSerializer = new BinaryFormatter(); obj =(T)binSerializer.Deserialize(fileStream); } return obj; }
测试:
static void Main(string[] args) { ArrayList list = new ArrayList() { "Zero", "One", "Two" }; SerializeHelper.SerializeToFile(list, "HT.data"); ArrayList list2 = SerializeHelper.DeserializeFromFile<ArrayList>("HT.data"); foreach (var item in list2) { Console.WriteLine(item.ToString()); } Console.ReadKey(); }
2.对象与字节流之间序列化/反序列化
public static byte[] Serialize<T>(T obj) { using (MemoryStream memStream = new MemoryStream()) { BinaryFormatter binSerializer = new BinaryFormatter(); binSerializer.Serialize(memStream, obj); return memStream.ToArray(); } } public static T Deserialize<T>(byte[] serializedObj) { T obj = default(T); using (MemoryStream memStream = new MemoryStream(serializedObj)) { BinaryFormatter binSerializer = new BinaryFormatter(); obj = (T)binSerializer.Deserialize(memStream); } return obj; }