有時候程式發生異常,用戶正在編輯數據突然系統就蹦了,為了避免用戶已經編輯的數據丟失,最好將用戶正在操作的數據進行本地持久化 ...
有時候程式發生異常,用戶正在編輯數據突然系統就蹦了,為了避免用戶已經編輯的數據丟失,最好將用戶正在操作的數據進行本地持久化
/// <summary>
/// 將對象序列化後保存到文件中
/// </summary>
public static void SerializeToFile<T>(T obj, string dataFile) {
using(FileStream fileStream = File.Create(dataFile)) {
BinaryFormatter binSerializer = new BinaryFormatter();
binSerializer.Serialize(fileStream, obj);
}
}
/// <summary>
/// 從文件中讀取數據並反序列化成對象
/// </summary>
public static T Deserialize<T>(string dataFile) {
T obj = default(T);
using(FileStream fileStream = File.OpenRead(dataFile)) {
BinaryFormatter binDeserializer = new BinaryFormatter();
obj = (T)binDeserializer.Deserialize(fileStream);
}
return obj;
}
Dictionary<string, object> transactionData = new Dictionary<string, object>() {
{ "Account","6226221601798333"},
{ "Name","張三"},
{ "TradeType","存款"},
{ "Amount",100.00d}
};
SerializeToFile(transactionData, "TD.txt");
var currentData = Deserialize<Dictionary<string, object>>("TD.txt");
foreach(var item in currentData) {
Console.WriteLine("{0}-{1}",item.Key,item.Value);
}