原创,转载请注明出处
经常,会碰到这种情况,程序运行后,用户在窗体的很多个textbox checkbox等控件输入了很多内容,而且这些控件分布在程序的各个页面,数量非常多。当退出后再运行时,需要保持退出时的内容不变。
最直接的办法是针对每个控件,退出时把内容保存到本地文件,启动时调用。但这存在较大问题,需要逐个获取控件的控件名,数量多了会让人发疯。而且每次增加或者删除一个textbox,都要修改保存和调用的代码。
为了解决这个问题,就有了这篇文章。思路很简单,退出时,遍历所有的控件,将需要保存的控件名称及内容保存到一个Dictionary对象里面,然后序列化,保存为文件。再启动时,读取该文件,并反序列化为Dictionary对象,再遍历所有的控件,将内容一一填入。
static string settingpath = AppDomain.CurrentDomain.BaseDirectory + "setting.dat";
private void GetControls(Control.ControlCollection fatherControl, ref Dictionary dic)
{
foreach (Control control in fatherControl)
{
if (control is TextBox && (control as TextBox).Multiline==false)//多行的textBox不保存
{
dic.Add(control.Name, control.Text);
//mylog(control.Name + "=" + control.Text);//test
}
if (control is CheckBox)//复选框
{
dic.Add(control.Name, (control as CheckBox).Checked.ToString());
}
if (control.Controls != null)
{
GetControls(control.Controls, ref dic);
}
}
}
private void SetControls(Control.ControlCollection fatherControl, ref Dictionary dic)
{
foreach (Control control in fatherControl)
{
if ((control is CheckBox || control is TextBox) && dic.ContainsKey(control.Name))
{
string txt;
dic.TryGetValue(control.Name, out txt);
if (control is CheckBox)
{
(control as CheckBox).Checked = txt == "True";
}
else//TextBox
{
control.Text = txt;
}
}
if (control.Controls != null)
{
SetControls(control.Controls, ref dic);
}
}
}
private Dictionary SettingfiletoDic()
{
Dictionary dic = null;
if (File.Exists(settingpath))
{
FileStream fs = new FileStream(settingpath, FileMode.Open, FileAccess.Read);
if (fs.Length > 0)
{
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
ms.Position = 0;
var bfmt = new BinaryFormatter();
dic = (Dictionary)bfmt.Deserialize(ms);
}
fs.Close();
fs.Dispose();
}
return dic;
}
private void saveallpara()
{
Dictionary dic = new Dictionary();
GetControls(Controls, ref dic);
if(dic.Count>0)
{
Dictionary olddic = SettingfiletoDic();
if (olddic != null && dic.SequenceEqual(olddic)) return;//内容无变化 无需保存
var bfmt = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bfmt.Serialize(ms, dic);
FileStream fs = new FileStream(settingpath, FileMode.OpenOrCreate, FileAccess.Write);
ms.Position = 0;
ms.CopyTo(fs);
fs.Flush();
fs.Close();
fs.Dispose();
}
}
private void loadallpara()
{
Dictionary dic = SettingfiletoDic();
if (dic != null) SetControls(Controls, ref dic);
}
代码一般放在form1.cs里面,以便能访问到Controls对象
程序启动时调用loadallpara(),退出时调用saveallpara()