1 、給類加上[Serializable]屬性 表示這個類是可以序列化
[csharp]
[Serializable]
public class Userinfo
{
public string uname { get; set; }
public string upass {get;set;}
public int IsSave { get; set; }
}
2、將對象序列化到文件中
[csharp]
//序列化
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、從文件反序列化為對象
[csharp]
//反序列化
FileStream fs = new FileStream(@"D:\serializeDem.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
Userinfo model = bf.Deserialize(fs) as Userinfo;
摘自 歐陽小燕