2013-04-07 92 views
8

我想读的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> 

回答

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

这不是一个问题的答案,直到它解释了代码做什么,以及为什么它解决了他的问题。 – 2013-04-07 11:27:19

9

它可以帮助你

试图挽救这样

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

你的代码为我工作。谢谢! – jned29 2016-08-08 09:45:36

+0

这里的关键语句是'config.AppSettings.SectionInformation.ForceSave = TRUE'。 – Tarik 2016-09-13 17:24:17

2

这应该从盘重装app.config文件:

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