How to write to a Configuration File

Previously I explained you how configuration files worked and how to retrieve settings from your configuration file to your code. Today I’ll show you how to make changes to your configuration file at runtime.

First you need to instantiate the Configuration object by using the OpenExeConfiguration method.
Use the OpenExeConfiguration method with the right ConfigurationUserLevel enumeration, to open the configuration file for the current application.
After initializing the object, it will be possible to add or edit settings in the configuration file.
Finally you need to save your changes, using the ConfigurationSaveMode enumeration.

Example configuration file with one setting named “Date”:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Date" value="" />
  </appSettings>
</configuration>

Example application code to change the “Date” key value to the current date time at runtime:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Date"].Value = DateTime.Now.ToString();
config.Save(ConfigurationSaveMode.Modified);

Result of the configuration file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Date" value="26/01/2012 10:27:21" />
  </appSettings>
</configuration>

It’s also possible to specify a configuration file to edit, so you can for instance change the configuration file of an other application.
To do this, you will need to create a configuration file map and specify this configuration file map in the OpenMappedExeConfiguration method when initializing the Configuration object.

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap { ExeConfigFilename = "C:\\Development\\Example.config" };
       
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["Date"].Value = DateTime.Now.ToString();
config.Save(ConfigurationSaveMode.Modified);

You can force the save by passing the “true” flag as second argument in the Save method. This will save every configuration setting in the configuration file.

config.Save(ConfigurationSaveMode.Modified, true);
Advertisements

Comments are closed.

%d bloggers like this: