序列化与反序列化
经过比较多种序列化方式,最终决定使用xml序列化,使用xml序列化可以不对类添加属性标签。
定义序列化与反序列化
private void SerializeObject(object obj, string filename)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
System.IO.TextWriter writer = new System.IO.StreamWriter(filename);
serializer.Serialize(writer, obj);
writer.Close();
}
private object DeSerializeObject(object obj, string filename)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);
object obj1 = serializer.Deserialize(fs);
fs.Close();
return obj1;
}
使用序列化与反序列化
/// <summary>
/// 保存配置文件
/// </summary>
public void SaveFile()
{
this.SerializeObject(classCANChanel, "D:\test.xml");
}
/// <summary>
/// 加载配置文件
/// </summary>
public void LoadFile()
{
classCANChanel = (ClassCANChanel)this.DeSerializeObject(classCANChanel, "D:\test.xml");
}