14

我想读取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>
4

5 回答 5

13

它可以帮助你

尝试保存这样的配置

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);
于 2013-04-07T10:44:43.050 回答
3

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

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"]);
于 2013-04-07T10:41:10.810 回答
2

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

var appSettings = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location).AppSettings;
MessageBox.Show(appSettings.Settings["TheValue"].Value);
于 2017-12-28T22:44:57.197 回答
1

这就是你真正需要的。

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

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

于 2018-07-12T22:23:43.897 回答
1

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

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

于 2020-09-24T12:25:49.360 回答