Thursday, February 04, 2010

How to Change .NET Configuration Files at Runtime (including for WCF)

One of the most common issues people run into with WCF configuration, and .NET applications in general, is that configuration files appear to be fixed. You only have one configuration file for an executable, and you can’t use different configuration files as your exe.config while the application is running. Of course, you can always shut down the application, change the configuration, and then restart it with the new configuration file, but that’s tedious and oftentimes undesirable. In this blog post, I’ll show you how to easily get around this limitation.

Suppose you have the following simple configuration file:

<configuration>

 <appSettings>

   <add key="name" value="foo"/>

 </appSettings>

</configuration>

And let’s say you have the following code:

public static void Main()

{

   Console.WriteLine(ConfigurationManager.AppSettings["name"]);

   ChangeConfiguration();

   Console.WriteLine(ConfigurationManager.AppSettings["name"]);

}

static void ChangeConfiguration()

{

   Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);

   AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");

   appSettings.Settings.Clear();

   appSettings.Settings.Add("name", "bar");

   config.Save();

}

Read more: Youssef Moussaoui's WCF blog

Posted via email from jasper22's posterous