Changing appconfig value at runtime

Sometimes there is the need to modify the value of some part of the configuration file of a.NET application at runtime, this is an example: I have a software that read some content from xml files, and have several paths listed in the AppSettings section of application configuration file.

During the very first run the software should extract xml data from a zip file to a directory chosen by the user, then the software should update all these settings to reflect this changes. Here is the code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
DirectoryInfo di = new DirectoryInfo(xmlFileLocation)
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
foreach (KeyValueConfigurationElement setting in config.AppSettings.Settings)
{
if (setting.Key.StartsWith("docroot"))
{
setting.Value = di.FullName;
}
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

With this code I cycle to all path that begins with docroot, (there are many of them in app.config) and then change all of them pointing to the new folder, then save the application config again.

alk.