如何重新加载/刷新app.config ?



我想读取app.config值,在消息框中显示它,使用外部文本编辑器更改值,最后显示更新的值。

我尝试使用以下代码:

private void button2_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    ConfigurationManager.RefreshSection("appSettings");
    ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
    MessageBox.Show(ConfigurationManager.AppSettings["TheValue"]);
}

但是它不起作用。它显示旧值(在外部文本编辑器中更改之前)。有什么建议吗?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
  <add key="TheValue" value="abc"/>
</appSettings>
</configuration>

它可能对你有帮助

尝试像这样保存配置

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["KeyName"].Value = "NewValue";
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);

然后像这样获取

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

您可以尝试使用以下代码:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = config.AppSettings.Settings;            
// update SaveBeforeExit
settings["TheValue"].Value = "WXYZ";
config.Save(ConfigurationSaveMode.Modified);
MessageBox.Show(ConfigurationManager.AppSettings["TheValue"]);

这会从磁盘重新加载app.config文件:

var appSettings = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location).AppSettings;
MessageBox.Show(appSettings.Settings["TheValue"].Value);

这就是你真正需要的。

System.Configuration.ConfigurationManager.RefreshSection("appSettings");
MessageBox.Show(System.Configuration.ConfigurationManager.AppSettings["TheValue"]);

可能的问题是,你正在修改错误的App.config文件。我自己也这么做了,觉得很傻。如果您使用IDE来测试代码,请更改bin目录中的YourAppName.vshost.exe.config文件。希望这对你有帮助!

如果你正在使用应用程序的属性设置(Properties.Settings.Default.Xxxx)你可以使用

Properties.Settings.Default.Reload ();var x = Properties.Settings.Default.Xxxx;//x将从config

获取新值

最新更新