【问题标题】:Change in application configuration without application restart无需重新启动应用程序即可更改应用程序配置
【发布时间】:2011-08-10 19:18:02
【问题描述】:

我有以下问题:我正在向应用程序中引入新功能(作为 Windows 服务运行),我希望使用某种配置文件条目(myKey)。我可以在 app.config 中存储配置条目,但如果我想将其从 on->off 更改,否则需要重新启动 Windows 服务,我想避免它。我希望我的应用程序能够运行并获取配置更改。

问题是:.NET 中是否存在解决该问题的内置机制?我想我可以创建自己的配置文件,然后使用FileSystemWatcher 等...但也许.NET 允许使用外部配置文件并重新加载值??

ConfigurationManager.AppSettings["myKey"]

谢谢,帕维尔

编辑 1:感谢您的回复。但是我写了以下 sn-p 并且它不起作用(我尝试在两个地方创建 appSettingSection:循环前和循环内):

static void Main(string[] args)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // AppSettingsSection appSettingSection = (AppSettingsSection)config.GetSection("appSettings");
    for (int i = 0; i < 10; i++)
    {
        ConfigurationManager.RefreshSection("appSettings");
        AppSettingsSection appSettingSection = (AppSettingsSection)config.GetSection("appSettings");
        string myConfigData = appSettingSection.Settings["myConfigData"].Value; // still the same value, doesn't get updated
        Console.WriteLine();
        Console.WriteLine("Using GetSection(string).");
        Console.WriteLine("AppSettings section:");
        Console.WriteLine(
          appSettingSection.SectionInformation.GetRawXml()); // also XML is still the same
        Console.ReadLine();
    }
}

当应用程序在 Console.ReadLine() 上停止时,我手动编辑配置文件。

【问题讨论】:

    标签: c# .net app-config configuration-files


    【解决方案1】:

    加载原始 app.config 文件后,它的值会被缓存,因此您必须重新启动应用程序。解决这个问题的方法是创建一个新的配置对象并像这样手动读取密钥:

    var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
    string myConfigData = appConfig.AppSettings.Settings["myConfigData"].Value;
    

    【讨论】:

    • 谢谢!但是仍然:每次访问 myConfigData 时,我都必须创建新的配置对象,以确保 appConfig.AppSettings.Settings["myConfigData"].Value 与 app.config 文件中的基础值一致?跨度>
    • 只需在调用appConfig.AppSettings.Settings["myConfigData"].Value; 之前调用ConfigurationManager.RefreshSection("appSettings");,这将强制应用程序读取新的和更改的设置。否则,ConfigurationManager 会固有地缓存所有值。
    • @TeomanSoygul RefreshSectioncall 更新通过ConfigurationManager.AppSettings[] 检索到的值,它不会影响配置实例。
    【解决方案2】:

    如果您手动处理配置(甚至可能不在 app.config 文件中),那么您可以定期检查该文件是否有更新。

    FileSystemWatcher 是......可能有点矫枉过正,并且在所有情况下都不能保证。就个人而言,我只是每(比如)30 秒轮询一次文件。

    【讨论】:

    • 嗨,你的意思是使用@Teoman Soygul 描述的解决方案进行池化。我觉得每 1 分钟重新加载一次设置会满足我的需求。
    • @dragonfly 好吧,有点;虽然我可能不一定使用 app-config 路径。不过,任何路线都可以;这不需要很复杂。
    【解决方案3】:

    在读取值之前,只需从当前配置文件中刷新“appSettings”:

    ConfigurationManager.RefreshSection("appSettings"); // Reload app settings from config file
    ConfigurationManager.AppSettings["myKey"];          // Read the value as usually
    

    无需通过创建另一个配置或配置或您的问题或其他答案中的任何建议来使其过于复杂!

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 1970-01-01
      相关资源
      最近更新 更多