让你的用户数据序列化通过添加关键字:
[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