Getting your app.config from an alternative source

UPDATE: Something has rotted in this code! Don’t use, but read more here.

Plodding along the course of my previous posting on how to decouple the log4net application file, it is often useful to do the same for the basic app.config, whether you want to share one common app.config between applications or  factor out some common settings.

Looking in vain at first, I began coding this functionality myself based on an XDocument, but today I found how to do this with the framework ConfigurationManager (this article on CodeProject). Wasted time, perhaps, but (hopefully) I am now a bit wiser!

For some reason the custom file Configuration manager does not return an object compatible with System.Configuration.ConfigurationManager.AppSettings, which uses a System.Collections.Specialized.NameValueCollection. Either it proves tha MS developers & architects are human, or there may be some reason which I just can’t guess.

Anyway, this is my workaround to make the two kinds of AppSettings interchangeable:

using System.Collections.Specialized;

public static class CustomFileConfigurationManager
{
    public static NameValueCollection AppSettings(string configFile)
    {
        var settings =
            System.Configuration.ConfigurationManager.OpenExeConfiguration(configFile).AppSettings.Settings;
        NameValueCollection appsettings = new NameValueCollection();
        foreach (var key in settings.AllKeys) appsettings.Add(key,settings[key].Value);
        return appsettings;
    }
}

Don’t forget to add System.Configuration to your references.

Advertisements
Posted in C#