1、在使用序列化BinaryFormat类的时候必须引入命名空间:
using System.Runtime.Serialization.Formatters.Binary;
2、设计类的时候,必须在类前面加上----对象可序列化标记
[Serializable]
public Class Student{...}
3、序列化
Student objStudent = new Student(){}; //对象初始化器 FileStream fs = new FileStream(dir,FileMode.Create); BinaryFormat formatter = new BinaryFormatter(); formatter.Serialize(fs,objStudent); fs.Close();
4、反序列化
FileStream fs = new FileStream(dir,FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); Student objStudent = (Student)formatter.Deserialize(fs); //反序列化方法放回object类型,需要强制转换 fs.Close();