Jump to content

Using different .config file in .NET application

Posted on:June 1, 2011 at 02:00 AM

In .NET world executable files using by default configuration file with special name. Microsoft has implemented following pattern: executable: program.exe and corresponding configuration file program.exe.config. In many scenarios this pattern is fitting well, but there are some cases when something else necessary. In my situation common configuration file was desirable! One configuration file with shared app settings, configuration strings, etc.

First solution I found was sharing AppSettings section between configuration files. This can be easily achieved by adding file attribute in appSettings tag. Like this:

<appSettings file="commonSettings.config">

But this doesn’t solve problem with connections string and custom sections… damn…

The solution that I end up with is:

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"commonConfig.config");

FieldInfo fiInit = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic ' BindingFlags.Static);

if (fiInit != null)
{
fiInit.SetValue(null, null);
}

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

The AppDomain.CurrentDomain.SetData() method changes properties for current domain. So I simply change the APP_CONFIG_FILE property value to point to another config file. Rest of the code is necessary to re-read the configuration. With this solution I able to force .NET to use one configuration file between multiple executables.