【问题标题】:How do I reload/refresh app.config?如何重新加载/刷新 app.config?
【发布时间】:2013-03-29 11:46:54
【问题描述】:

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

【问题讨论】:

    标签: c# .net app-config config


    【解决方案1】:

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

    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】:

    也许对你有帮助

    尝试像这样保存配置

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

    【讨论】:

    • 这里的关键声明是config.AppSettings.SectionInformation.ForceSave = true
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      这就是你真正需要的。

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

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

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-01
          • 2011-02-23
          • 2010-10-31
          • 2017-04-12
          • 1970-01-01
          • 1970-01-01
          • 2010-12-03
          • 1970-01-01
          相关资源
          最近更新 更多