December 17, 2013, 10:59 AM — App.config and Web.config files are a great way to add flexibility to your .NET application without having to modify code in the future. They also allow clients or end users to make configuration changes without the help of a developer. Here’s how to go about leveraging the built in Configuration libraries to enable your own custom sections and settings.
You’re probably familiar with the <appSettings> section in the config files which allow you to quickly and easily add key/value pair data to your application. While convenient, these appSettings are limited to those two specific data attributes and you can’t always fit your requirements into them.
To solve this problem, you can create your own custom configSection that you can define the schema for.
The first step is to define your XML schema for storing your settings. In this example I’ll keep it pretty basic and we’ll imagine we’re storing a list of files to process into HTML with a source and destination path.
Next we need to make the config file aware of the custom section by adding the section declaration to the configSections element in the Web.config or App.config file. If there is no configSections element, create one at the top of the file just after the opening configuration tag.
Now that we’ve got our settings into the config file, we have to let the .NET configuration provider know how to handle them. To do this, we need to create a few classes that inherit from some System.Configuration classes. For simplicity’s sake, I’ll build all of the classes into a single file called FileRetriever.cs.
The first class is the FileRetriever class. This class provides static access to the data in the configSection.
Then comes the FileRetrieverSection class which inherits from ConfigurationSection. This tells .NET to look for a root element called “files” and return a collection of FileElements for each entry under files.
Next is the FileElementCollection class. This provides access to the individual FileElements in the collection and defines a Key for each element in the collection.
Finally, and of most interest, is the FileElement class. This class is how you map your XML schema to a .NET object for consumption. You define a property for each attribute in your schema and you set meta data on each property to describe it’s use and requirements. It’s important to note that one of your properties must be defined as the Key, usually Name is the obvious choice.
With the above up and running, you’re now able to access your settings throughout your application in a simple and intuitive manner. For example, to iterate over each file and perform work it’s as easy as: