//name 键
//value 值
public static bool SetAppSettings(string name, string value)
{
try
{
//获取配置文件
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);//当前应用程序的配置文件
if (config != null)
{
//获取appsettings部分
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
if (appSettings.Settings.AllKeys.Contains(name))
{
//更新键值
appSettings.Settings[name].Value = value;
}
else
{
//键不存在,添加键值对
appSettings.Settings.Add(name, value);
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");; //保存配置文件
return true;
}
return false;
}
catch(Exception ex)
{
Console.WriteLine(String.Format("修改app.config配置{0}的值为{1}异常:{2}", name, value, ex.Message));
return false;
}
}
C# 更新修改 .config配置文件中的appsettings键值对
于 2024-05-16 08:52:26 首次发布