1 、给类加上[Serializable]属性 表示这个类是可以序列化
[Serializable]
public class Userinfo
{
public string uname { get; set; }
public string upass {get;set;}
public int IsSave { get; set; }
}
2、将对象序列化到文件中
//序列化
FileStream fs = new FileStream(@"D:\serializeDem.dat", FileMode.Create);
Userinfo model = new Userinfo() { uname= "admin",upass="admin" IsSave = 1 };
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, model);
fs.Close();
3、从文件反序列化为对象
//反序列化
FileStream fs = new FileStream(@"D:\serializeDem.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
Userinfo model = bf.Deserialize(fs) as Userinfo;