Reputation: 17773
I have following issue: I'm introducing new feature into application (run as Windows Service) and I would like to have that new feature controlled (on/off) using some kind of configuration file entry (myKey). I can store config entry in app.config but if I want to change it from on->off or otherwise it would require to restart Windows Service, and I want to avoid it. I want my application to run and pick up changes in configuration.
The question is: is there a build in mechanism in .NET that addresses that problem ? I guess I could create my own config file, then use FileSystemWatcher
etc... But perhaps .NET allows to use external config files and will reload value ??
ConfigurationManager.AppSettings["myKey"]
Thanks, Pawel
EDIT 1: Thanks for replies. However I wrote following snippet and it doesn't work (I tried creating appSettingSection in both places: before and inside loop):
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();
}
}
I manually edit config file when application stops on Console.ReadLine().
Upvotes: 6
Views: 9944
Reputation: 608
Simply refresh the "appSettings" from current config file before you read the value:
ConfigurationManager.RefreshSection("appSettings"); // Reload app settings from config file
ConfigurationManager.AppSettings["myKey"]; // Read the value as usually
No need to over complicate it by creating another config or configuration or what so ever suggested in your question or other answers!
Upvotes: 0
Reputation: 1062895
If you process the configuration manually (perhaps not even in the app.config file), then you can periodically check that file for updates.
FileSystemWatcher
is... probably overkill, and isn't guaranteed in all scenarios. Personally, I'd just poll the file every (say) 30 seconds.
Upvotes: 1
Reputation: 25742
Once the original app.config file is loaded, it's values are cached so as you know, you'll have to restart the app. The way around this is to create a new config object and read the keys manually like this:
var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
string myConfigData = appConfig.AppSettings.Settings["myConfigData"].Value;
Upvotes: 6