在运行时从配置文件写入和读取更新的 appSettings

Write and read updated appSettings from config file during runtime

问题:

我有一个程序,我在运行时在我的 appconfig 中写入 Keys+Values,但是当我想读取它们时,我得到了旧值,而获得新值的唯一方法是重新启动应用程序。

只要我以编程方式编写键+值,配置文件就会更新,所以这不是问题,但我不明白为什么我不会在同一运行时获得新值。

我这样写: (尝试使用和不使用 RefreshSection(key) - 没有区别)

public static void AddValue(string key, string value)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
    config.AppSettings.Settings.Add(key, value);
    config.Save(ConfigurationSaveMode.Full);
    ConfigurationManager.RefreshSection(key);
}

我是这样读的:

string[] ItemsArray = ConfigurationManager.AppSettings["Items"].Split(',');

问题:

如何读取我在同一运行时添加的新密钥(在运行时)?

你应该试试

ConfigurationManager.RefreshSection("appSettings");

在这里找到一个旧的 post Reloading configuration without restarting application using ConfigurationManager.RefreshSection