This is a quick guide to get you up and running with the .NET 2.0 Configuration framework that also answers some of the frequently asked questions. If you are after an in-depth explanation of the .NET 2.0 Configuration framework you will probably find what you need in this article on The Code Project. It does a great job at explaining each part of the framework extensively, as well as give you some examples to work with. I recommend it.

Typical scenario

  1. Windows Forms application
  2. The application has some settings the users can change
  3. You want an easy and quick way of saving the application's settings to a file, loading them when he application starts and allowing the users to change them while the application is running.

One way to go about it would be to specify an XML file (e.g. ApplicationSettings.xml) and use the System.XML namespace and its classes to write to and read from it. It is not difficult and it will work, but you will be saving yourself some time and effort if you just leverage the .NET 2.0 Configuration Framework as it already does a lot of what you want to do.

Step 1 

First of all add an app.config to your application. Since the app.config file can be used to specify various .NET related settings and options for your application, I like to keep the real "application settings" seperate from it, so I use a seperate file for that. Create a new configuration section and point it to a seperate file by adding the following XML element in the app.config

<applicationSettings configSource="ApplicationSettings.xml" />

My new configuration section is called "applicationSettings" and its contents are in the file "ApplicationSettings.xml". This is a relative path, but a fully qualified path can also be used. Create the "ApplicationSettings.xml" file and add one of the settings in it.

<applicationSettings restorePositionOnOpen="true">
</applicationSettings>

I have chosen to add a setting that has a "true" or "false" value and is called "restorePositionOnOpen".

Step 2 

Now its time for some simple code. This is the main part were you will be saving yourself time if you use the .NET 2.0 Configuration framework. You will need a class that gives you programatic access to the application settings. All that is necessary is a new class that inherits from "ConfigurationSection" and some properties that will allow to get or set each application setting.

public class ApplicationSettings : ConfigurationSection
{
    [ConfigurationProperty("restorePositionOnOpen")]
    public bool RestorePositionOnOpen
    {
       get { return (bool)this["restorePositionOnOpen"]; }
       set { this["restorePositionOnOpen"] = value; }
    }
}

The class is called "ApplicationSettings" and inherits from "ConfigurationSection". It contains a single property called "RestorePositionOpen" that just gets or sets the value of the XML attribute "restorePositionOnOpen" in the "ApplicationSettings.xml" file. The property is annotated with the attribute "[ConfigurationProperty("storePositionOnOpen")]" so that the .NET 2.0 Configuration Framework knows how to bind the configuration section and the classes's properties.

Step 3

All that remains now is tell the  .NET 2.0 Configuration Framework to use the class "ApplicationSettings" for the configuration section "applicationSettings". This is done by adding the following XML element in the app.config file

<configSections>
     <section name="applicationSettings" type="Namespace.ApplicationSettings, AssemblyName" />
</configSections>

That is it, you now have an XML file separate to app.config that holds your application's settings and you can programmatically access it through the class "ApplicationSettings".

Saving changes

By default the configuration settings are read only, so when you try to set the value of a property an exception will be thrown. The solution is quite simple, you need to load the configuration using "OpenExeConfiguration(...)"

/// <summary>
/// Gets the application's settings.
/// </summary>
public
static ApplicationSettings Settings
{
    get
    {
        // If the configuration file has not been loaded yet
        if (MainForm.configuration == null)
        {
            // Load the configuration file from disk
            MainForm.configuration =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        }

        return (ApplicationSettings) configuration.Sections["applicationSettings"];
    }
}

By keeping a class scope reference of the configuration class, it is possible to save the changed made to the settings at any point necessary. For example

protected override void OnClosed(EventArgs e)
{
    // Perform the standard logic during close 
    base.OnClosed(e);
      
    // Save the changes made to the configuration file 
    MainForm.configuration.Save();
}


Beyond the basics

You can build on this to create a rather sophisticated solution for your application settings. Configuration settings that are accessed through properties can be marked as mandatory and you can even specify default values for when they are missing. This way you can introduce new settings to your application as part of a new version keeping compatibility with settings files from older versions. You can even have validation take place at the time of loading the values from the configuration file to ensure that it has not been changed outside the application to something invalid. Check out the ConfigurationPropertyAttribute spec for all this and more ...

You may decide to have different settings for each user, in which case you'd need to load the appropriate configuration for the user corrently logged in. Check out the details of the OpenExeConfiguration method for more information.