class SetConfig
{
//获取AppConfig
public static string GetAppConfig(string strKey)
{
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == strKey)
{
return ConfigurationManager.AppSettings[strKey];
}
}
return null;
}
//更新配置节
public static void UpdateAppConfig(string newKey, string newValue)
{
bool isModified = false;// 记录该Key是否已经存在
// 如果要更改的Key已经存在
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == newKey)
{
isModified = true;
}
}
//打开 App.Config
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 如果连接串已存在,首先删除它
if (isModified)
{
config.AppSettings.Settings.Remove(newKey);
}
//添加新的配置到配置文件里
config.AppSettings.Settings.Add(newKey, newValue);
//保存对配置节所做的更改
config.Save(ConfigurationSaveMode.Modified);
//强制重载配置节
ConfigurationManager.RefreshSection("appSettings");
}
}
{
//获取AppConfig
public static string GetAppConfig(string strKey)
{
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == strKey)
{
return ConfigurationManager.AppSettings[strKey];
}
}
return null;
}
//更新配置节
public static void UpdateAppConfig(string newKey, string newValue)
{
bool isModified = false;// 记录该Key是否已经存在
// 如果要更改的Key已经存在
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == newKey)
{
isModified = true;
}
}
//打开 App.Config
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 如果连接串已存在,首先删除它
if (isModified)
{
config.AppSettings.Settings.Remove(newKey);
}
//添加新的配置到配置文件里
config.AppSettings.Settings.Add(newKey, newValue);
//保存对配置节所做的更改
config.Save(ConfigurationSaveMode.Modified);
//强制重载配置节
ConfigurationManager.RefreshSection("appSettings");
}
}
本文深入探讨了如何通过配置管理获取和更新App配置项,包括解析App.Config文件及实现配置更新的步骤。
982

被折叠的 条评论
为什么被折叠?



