Refresh AppSettings keys

The .Net runtime caches the app.config file, therefore, when the app.config file is updated, you often need to restart the application in order for the changes to show up. Sure, you can get the keys by calling ConfigurationManager.OpenExeConfiguration() and you would be getting the latest version of the config file every time, but it's probably not the most efficient way to do it.

Here is how I like to do it. I call ConfigurationManager.AppSettings["MyAppSetting"] to get my key, which gets the cached version of the key so it's very fast. And I use a file system watcher to watch for changes in the config file. Whenever the config file is updated, I call ConfigurationManager.RefreshSection("AppSettings") to refresh the app settings keys. This way, the application would not have to be restarted whenever the config file changes.

Here is what the class might look like.

using System;
using System.Configuration;
using System.IO;
 
namespace myApp
{
    /// <summary>
    /// This class will refresh the cached version of the config file when it is changed.
    /// </summary>
    public static class ConfigurationWatcher
    {  
        private static FileSystemWatcher _fileWatcher;   
 
        internal static void Start()
        {
            if (_fileWatcher == null)
            { 
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                string path = Path.GetDirectoryName(config.FilePath);
                string filename = Path.GetFileName(config.FilePath);                   
 
                _fileWatcher = new FileSystemWatcher();
                _fileWatcher.Path = path;
                _fileWatcher.Filter = filename;
                _fileWatcher.NotifyFilter = (NotifyFilters.CreationTime | NotifyFilters.LastWrite |
                                NotifyFilters.FileName);
                _fileWatcher.Changed += OnChange;
                _fileWatcher.EnableRaisingEvents = true;
            }           
        }
 
        private static void OnChange(object source, FileSystemEventArgs e)
        {
            ConfigurationManager.RefreshSection("AppSettings");
        }
    }
}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
«March»
SunMonTueWedThuFriSat
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234