更改应用程序配置而不重新启动应用

dra*_*fly 7 .net c# app-config configuration-files

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

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

ConfigurationManager.AppSettings["myKey"]
Run Code Online (Sandbox Code Playgroud)

谢谢,Pawel

编辑1:谢谢你的回复.但是我编写了以下代码片段并且它不起作用(我尝试在两个地方创建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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Teo*_*gul 6

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

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

  • 在调用`appConfig.AppSettings.Settings ["myConfigData"]之前调用`ConfigurationManager.RefreshSection("appSettings");`.值;`这将强制应用程序读取新的和更改的设置.否则,`ConfigurationManager`固有地缓存所有值. (11认同)