首页 > 代码库 > C# 不重启程序修改并保存配置文件(appSettings节点)

C# 不重启程序修改并保存配置文件(appSettings节点)

private static void UpdateAppConfig(string newKey, string newValue)
{
    bool isModified = false;
    foreach (string key in ConfigurationManager.AppSettings)
    {
        if (key == newKey)
        {
            isModified = true;
        }
    }
    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");
}

 

之后直接用ConfigurationManager.AppSettings[key]读取就行了。

 

C# 不重启程序修改并保存配置文件(appSettings节点)