我有以下问题:我正在将新功能引入应用程序(作为Windows服务运行),我希望使用某种配置文件条目(myKey)来控制新功能的开启和关闭。我可以将配置条目存储在app.config中,但如果我想从开启到关闭或者反过来进行更改,那么就需要重新启动Windows服务,而我想避免这种情况。我希望我的应用程序能够运行并且能够获取配置文件的更改。
问题是:.NET是否有内置机制来解决这个问题?我猜我可以创建自己的配置文件,然后使用
问题是:.NET是否有内置机制来解决这个问题?我猜我可以创建自己的配置文件,然后使用
FileSystemWatcher
等等...但也许.NET允许使用外部配置文件并重新加载值?ConfigurationManager.AppSettings["myKey"]
谢谢,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();
}
}
当应用程序停止在Console.ReadLine()时,我会手动编辑配置文件。
appConfig.AppSettings.Settings["myConfigData"].Value;
之前,只需调用ConfigurationManager.RefreshSection("appSettings");
即可强制应用程序读取新的和已更改的设置。否则,ConfigurationManager
会默认缓存所有值。请注意不要改变原文的意思。 - Teoman SoygulRefreshSection
调用会更新通过ConfigurationManager.AppSettings[]
检索到的值,但不会影响配置实例。 - SerG