Thursday, August 27, 2009

Saving Data to the Configuration (*.config) File

Sometimes you want to save data to the configuration file so it's available the next time the application runs. An example of this is saving a window's last height and width upon closing. Here's how you do it:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings.Remove("Width");
config.AppSettings.Settings.Add("Width", this.Width.ToString());
config.AppSettings.Settings.Remove("Height");
config.AppSettings.Settings.Add("Height", this.Height.ToString());

config.Save(ConfigurationSaveMode.Modified);

Mark, why do I have to call the Remove method before adding?

Every time you call the Add method it appends data instead of overwriting it. Without calling the Remove method your configuration file will go from this:
<configuration>
    <appSettings>
        <add key="Width" value="402" />
        <add key="Height" value="177" />
    </appSettings>
</configuration>
to this on the next save:
<configuration>
    <appSettings>
        <add key="Width" value="402,300" />
        <add key="Height" value="177,154" />
    </appSettings>
</configuration>
More Info: MSDN: Configuration Class