2011-04-22 51 views
7

我有以下问题:我在引入新的功能到应用程序(如运行Windows服务),我会使用某种配置文件都喜欢有一个新的功能控制(开/关) (myKey)。我可以在app.config中存储配置条目,但是如果我想从on-> off进行更改,或者需要重新启动Windows Service,并且我想避免它。我希望我的应用程序能够运行并获取配置中的更改。变化的应用配置,而无需重新启动应用程序

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

ConfigurationManager.AppSettings["myKey"] 

此致的Pawel

EDIT 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(); 
    } 
} 

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

回答

7

一旦原始app.config文件被加载,它的值被缓存,因此你也知道,你将不得不重新启动应用程序。解决这个问题的方法是创建一个新的配置对象,并手动读取键这样的:

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

谢谢!但仍然:每当我访问myConfigData时,我都必须创建新配置对象,以确保appConfig.AppSettings.Settings [“myConfigData”]。值与app.config文件中的基础值一致? – dragonfly 2011-04-22 06:39:21

+11

只需拨打'ConfigurationManager.RefreshSection(“的appSettings”);'你调用'appConfig.AppSettings.Settings [“myConfigData”]前值;'这将迫使应用程序读取新的和更改的设置。否则,'ConfigurationManager'固有地缓存所有的值。 – 2011-04-22 06:41:46

+1

@TeomanSoygul'RefreshSection'通过'ConfigurationManager.AppSettings []'检索更新值,它不会影响配置实例。 – SerG 2014-11-20 11:50:46

1

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

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

+0

嗨,你的意思是使用@Teoman Soygul描述的解决方案进行池化。我每隔1分钟重新载入一次设置就能满足我的需求。 – dragonfly 2011-04-22 06:42:03

+0

@dragonfly很好,有点;虽然我可能不一定使用它的应用程序配置路径。任何路线都可以工作。这并不需要很复杂。 – 2011-04-22 06:43:58

相关问题