由于项目中多处需要对配置文件进行操作,如配置信息的读取、更改和写入,需要一个通用的类来对其进行操作和处理。
主要是对VS2005配置类的一些介绍及扩充(用户自定义配置节点的操作)。针对WinForm项目。
1. WinForm 项目
1.1 系统自带
在VS2005中,我们可以通过系统自带的管理类来读取和修改相应Key所对应的Value值,具体的方法如下(注意:由于key是之读属性,因此只能修改与key相对应的Value值):
传入相应的Key值(如Test),通过调用ConfigurationManager.AppSettings["Test"] .Value即可获得对应的Value值
1) 创建一个Configuration实例
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
2) 传入Key值通过调用下面方法来获取对应的值
如传入Key为Test参数来获取对应值:config.AppSettings.Settings["Test"].Value
3) 保存配置节
config.Save(ConfigurationSaveMode.Modified)
保存的构造函数有三种:
不带参数
带一个ConfigurationSaveMode参数
带一个ConfigurationSaveMode参数和bool型参数
ConfigurationSaveMode的参数有三种方式:
Full | 将所有属性都写到配置文件。在创建信息配置文件时或将配置值从一台计算机移动到另一台计算机时最有用 |
Minimal | 仅将不同于继承值的属性写出到配置文件。 |
Modified | 仅将修改的属性写出到配置文件,即使值和继承值相同。 |
1) 打开配置文件(Web.config)
Configuration config = ConfigurationManager.OpenWebConfiguration("../Web.Config ~");
2) 根据传入Key值来删除相应的配置节
如传入Key为Test参数来删除配置节:. config.AppSettings.Settings.Remove(Key);
internal static string CreateLocalAppSetting(string Key, string Value)
{
try
{
string[] strKeys = ConfigurationManager.AppSettings.AllKeys;
foreach (string strKey in strKeys)
{
if (strKey == Key)
{
return "EXISTS: This key[" + Key.Trim() + "] has already existed in configuration!";
}
}
string strPath = HttpRuntime.AppDomainAppPath + "web.config";
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = strPath;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
// Add an Application Setting.
config.AppSettings.Settings.Add(Key.Trim(), Value.Trim());
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
return "SUCCESS";
}
catch (Exception ex) { return ex.Message; }
}