Geeks With Blogs
HanSolo code monkey
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 |
                _fileWatcher.Changed += OnChange;
                _fileWatcher.EnableRaisingEvents = true;
        private static void OnChange(object source, FileSystemEventArgs e)
Posted on Saturday, March 7, 2009 5:11 PM | Back to top

Comments on this post: Refresh AppSettings keys

# re: Refresh AppSettings keys
Requesting Gravatar...
Yes thanks, Its working !!!
Left by Japan on Aug 10, 2009 8:14 AM

# re: Refresh AppSettings keys
Requesting Gravatar...
Excellent article!
Left by André Monteiro on Jan 19, 2010 12:46 PM

# A small typo
Requesting Gravatar...
Thanks for the example!
I just want to mention that there should be ConfigurationManager.RefreshSection("appSettings") instead of "AppSettings" (with capital "A").
Left by yallie on Apr 02, 2010 1:41 PM

# re: Refresh AppSettings keys
Requesting Gravatar...
I found this solution while searching for a resolution to the cached appSettings. Restarting IIS isn't always an option for use because there are a number of applications on the same server. Thanks, it was a huge help!
Left by Jim on Jun 17, 2010 3:59 AM

Your comment:
 (will show your gravatar)

Copyright © HanSolo | Powered by: