BinaryFormatter 类:
xml文件:
XmlSerializer serializer = new XmlSerializer(drawing.GetType());
using (FileStream writer = new FileStream(fileName, FileMode.Create))
{
serializer.Serialize(writer, drawing);
}
二进制文件序列化:
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream writer = new FileStream(fileName, FileMode.Create))
{
formatter.Serialize(writer, drawing);
}
二进制文件反序列化:
if (!File.Exists(fileName))
return null;
try
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream reader = new FileStream(fileName, FileMode.Open))
{
return (DnaDrawing)formatter.Deserialize(reader);
}
}
catch (Exception ex) { ; }
要序列化的类为Drawing,定义如下:
[Serializable]
public class Drawing
{
public List<Star> Stars { get; set; }
[XmlIgnore]
public bool IsDirty { get; private set; }
......
}
要序列化的类添加属性[Serializable],类中的字段不想序列化就加上[XmlIgnore];
字段中有自定义的类型,一层层下去,每层自定义类都要添加属性[Serializable]。