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

时间:2013-04-07 10:35:05

标签: c# .net app-config 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>

5 个答案:

答案 0 :(得分:10)

它可能对你有帮助

尝试像这样保存配置

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);

答案 1 :(得分:2)

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

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"]);

答案 2 :(得分:2)

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

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

答案 3 :(得分:1)

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

Properties.Settings.Default.Reload(); var x = Properties.Settings.Default.Xxxx; // x将从config中获取新值

答案 4 :(得分:0)

这就是您真正需要的。

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

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