有時候用戶進行了某些操作,想要一直保留這個記錄或者說服務器爲了保存用戶的信息或者狀態可以用BinaryFormatter
//=====以流的形式將對象進行序列化========
/// <summary>
/// 序列化
/// </summary>
static void Serialize()
{
List<string> strValue = new List<string>();
strValue.Add("哈哈");
strValue.Add("嘿嘿");
strValue.Add("呵呵");
strValue.Add("嘎嘎");
BinaryFormatter bf = new BinaryFormatter();
using (Stream stream = File.OpenWrite(@"H:\binary.xxx"))
{
bf.Serialize(stream, strValue);
}
}
// ==========將流反序列化成對象============
/// <summary>
/// 將流反序列化成對象
/// </summary>
static void Deserialize()
{
BinaryFormatter bf = new BinaryFormatter();
if (!File.Exists(@"H:\binary.xxx"))
{
throw new Exception("找不到對象存儲位置");
}
using (Stream stream = File.OpenRead(@"H:\binary.xxx"))
{
object obj = bf.Deserialize(stream);
List<string> listVlaue = (List<string>)(obj);
foreach (string str in listVlaue)
{
Console.WriteLine(str);
}
}
}
這樣只要進行一次序列化就會把序列化的信息以流的形式存儲到指定的位置,下次用可以直接取。用BinaryFormatter還可以序列化複雜的對象