准备序列化的类,类头上需要添加[Serializable]属性,表示该类可以被序列化
[Serializable]
public class HrRyxxData
{
public int __row_number__ { get; set; }
public string UID { get; set; }
public string XM { get; set; }
public string XBM { get; set; }
public string BZLBM { get; set; }
public string DQZTM { get; set; }
public string SZDWH { get; set; }
public override string ToString()
{
return "__row_number__:" + __row_number__ + "," +
"UID:" + UID + "," +
"XM:" + XM + "," +
"XBM:" + XBM + "," +
"BZLBM:" + BZLBM + "," +
"DQZTM:" + DQZTM + "," +
"SZDWH:" + SZDWH;
}
}
//序列化/反序列话一个“类”的List
private List<HrRyxxData> hrRyxxCacheDatas;
序列化
private void SaveCacheData()
{
using (FileStream fileStream = new FileStream(Path.Combine(Utility.AppDataPath, HR_RYXX_DATA_CACHE_FILENAME), FileMode.Create))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStream, hrRyxxDatas);
}
}
反序列化
private void LoadCacheData()
{
Utility.Log.Info("加载Cache数据...");
string cacheFileName = Path.Combine(Utility.AppDataPath, HR_RYXX_DATA_CACHE_FILENAME);
if (File.Exists(cacheFileName) == true)
{
if (new FileInfo(cacheFileName).Length > 0)
{
using (FileStream fileStream = new FileStream(cacheFileName, FileMode.Open))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
hrRyxxCacheDatas = binaryFormatter.Deserialize(fileStream) as List<HrRyxxData>;
return;
}
}
}
hrRyxxCacheDatas = new List<HrRyxxData>();
}