如何更新 .NET 中现有配置键的值?

How to update the value of an existing config key in .NET?

举个例子...

<add key="IDs" value="001;789;567"/>

如何以编程方式仅更新(追加)App.config 中现有键的值?

<add key="IDs" value="001;789;567;444"/>

我的代码目前有以下添加新键的代码,但我不知道如何更新键。

System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings.Add(appKey, appKeyValue);

// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);

您可以通过设置键或索引器访问它。

Configuration config = ConfigurationManager.OpenExeConfiguration("YourConfigFilePath");
config.AppSettings.Settings["IDS"].Value = "001;789;567;444";  // Update the value (You could also use your appKey variable rather than the string literal.

config.Save();

作为附加说明,导入 System.Configuration 命名空间可能比每次都使用 System.Configuration 别名更容易。