本文实例讲述了C#实现appSettings节点读取与修改的方法,分享给大家供大家参考。具体方法如下:
关键代码如下:
代码如下:
public static string GetAppSettingsValue(string key)
{
ConfigurationManager.RefreshSection(“appSettings”);
return ConfigurationManager.AppSettings[key] ?? string.Empty;
}
public static bool UpdateAppSettings(string key, string value)
{
var _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (!_config.HasFile)
{
throw new ArgumentException(“程序配置文件缺失!”);
}
KeyValueConfigurationElement _key = _config.AppSettings.Settings[key];
if (_key == null)
_config.AppSettings.Settings.Add(key, value);
else
_config.AppSettings.Settings[key].Value = value;
_config.Save(ConfigurationSaveMode.Modified);
return true;
}
{
ConfigurationManager.RefreshSection(“appSettings”);
return ConfigurationManager.AppSettings[key] ?? string.Empty;
}
public static bool UpdateAppSettings(string key, string value)
{
var _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (!_config.HasFile)
{
throw new ArgumentException(“程序配置文件缺失!”);
}
KeyValueConfigurationElement _key = _config.AppSettings.Settings[key];
if (_key == null)
_config.AppSettings.Settings.Add(key, value);
else
_config.AppSettings.Settings[key].Value = value;
_config.Save(ConfigurationSaveMode.Modified);
return true;
}
希望本文所述对大家的C#程序设计有所帮助。