Visual Studio .NET 2003Windows 2003.NET 1.1Windows 2000Windows XPWindows Forms中级开发Visual StudioWindows.NETC#
使用隔离存储轻松存储窗体和应用程序设置






4.67/5 (10投票s)
2005 年 1 月 26 日
1分钟阅读

88172

505
一种使用隔离存储轻松存储表单和应用程序设置的解决方案。
引言
隔离存储是一种保存用户特定数据的方式,类似于保存到注册表或老式的 .ini 文件。为了能够轻松使用隔离存储,我创建了一个小类,它使用简单的接口处理写入表单设置(位置和大小)和应用程序设置(例如用户首选项)。
背景
隔离存储的概念在这些文章中得到了很好的描述:.NET 中使用隔离存储存储应用程序数据 和 隔离存储简介。
IsolatedStorage.ConfigurationManager 类
IsolatedStorage.ConfigurationManager
类处理隔离存储的读取和写入。它具有以下特性:
- 所有设置都保存在 XML 文件中。
- XML 文件的名称与应用程序相同,但带有 .config 扩展名(例如:IsoStorageDemoCS.config)。
- 表单设置按表单名称保存。
- 保存的表单设置包括位置、状态和大小。
- 可以使用唯一的设置名称保存其他设置。
这是一个设置文件的示例:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<DemoText>CodeProject Rules!</DemoText>
<DemoChecked>True</DemoChecked>
<DemoCombo>4</DemoCombo>
<Form1WindowState>0</Form1WindowState>
<Form1>235,685,217,162</Form1>
</configuration>
该类的接口在以下部分中说明。
使用 IsolatedStorage.ConfigurationManager 类保存设置
要保存设置,只需两个调用就足够了。首先创建一个 IsolatedStorage.ConfigurationManager
,然后调用适当的 Write
方法。这是一个代码示例:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
config.Write("DemoText", txtDemo.Text);
config.Write("DemoChecked", chkDemo.Checked.ToString());
config.Write("DemoCombo", cmbDemo.SelectedIndex.ToString());
config.WriteFormSettings(this);
config.Persist();
}
使用 IsolatedStorage.ConfigurationManager 类检索设置
检索设置就像保存一样简单:
private void Form1_Load(object sender, System.EventArgs e)
{
IsolatedStorage.ConfigurationManager config =
GetConfigurationManager(Application.ProductName);
config.ReadFormSettings(this);
txtDemo.Text = config.Read("DemoText");
chkDemo.Checked = config.ReadBoolean("DemoChecked", false);
cmbDemo.SelectedIndex = config.ReadInteger("DemoCombo", 0);
}
总结
使用隔离存储来存储设置可以非常容易地完成。包含的演示项目提供了一个很好的示例。如有需要,VB.NET 代码可用。