讓你的用戶數據序列化通過添加關鍵字:
[Serializable]
數據結構之上。當你加載對話框時,從磁盤加載你的序列化結構,當你離開對話框時,保存數據結構。
從風格的角度來看,你應該沒有對話框改變數據,直到對話框關閉(如果它是模態的)。
爲了節省:
private bool Save(String inFileName, MyObject inObject){
try {
FileStream theStream = File.Open(inFileName, FileMode.Create);
BinaryFormatter theFormatter = new BinaryFormatter();
theFormatter.Serialize(theStream, inObject);//add it to the end there
theStream.Dispose();
theStream.Close();
} catch{
return false;
}
return true;
}
加載:
private MyObject Read(String inFileName){
MyObject theReturn = null;
try {
FileStream theStream = File.Open(inFileName, FileMode.Open, FileAccess.Read);
BinaryFormatter theFormatter = new BinaryFormatter();
theReturn = (CImageData)theFormatter.Deserialize(theStream);//add it to the end there
theStream.Dispose();
theStream.Close();
}
catch {
return null;
}
return theReturn;
}
你也可以使用一個流 '使用',但是這個代碼是非常簡單的,我想。這也意味着你可以添加更多的項目到MyObject中。
編輯:對於加密,您可以添加AES或類似的東西。這可能是矯枉過正的,並將文件保存爲二進制文件可能會使它像記事本一樣可讀,但不容易編輯。這裏有真正的加密冗長的解釋:
http://msdn.microsoft.com/en-us/magazine/cc164055.aspx
來源
2009-01-13 00:47:35
mmr