Custom ConfigurationSection from System.Configuration
Sometimes we forget about System.Configuration. This is plain when you find a project with its custom configuration xml parsing techniques. Maybe we all need to be reminded about System.Configuration. Say you want configuration that looks like this.
Let's start by the inner most element, directory. This is a class that inherits from System.Configuration.ConfigurationElement. Each property decorated with the ConfigurationPropertyAttribute is an attribute on the configuration element.
[ConfigurationProperty(PathIdentifier)] public string Path { get { return (string)this[PathIdentifier]; } set { this[PathIdentifier] = value; } } }
We need a configuration element that can hold a list of other configuration elements. This needs to inherit from System.Configuration.ConfigurationElementCollection. There are some more work involved telling the collection what inner element to expect.
public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } }
protected override string ElementName { get { return AddItemNameIdentifier; } }
public void Add(Directory directory) { BaseAdd(directory); }
protected override ConfigurationElement CreateNewElement() { return new Directory(); }
protected override object GetElementKey(ConfigurationElement element) { var instance = (Directory)element; return instance.Path; } }
Finally we can create the holder element, the ConfigurationSection. We reference the section from the <configSection> in the App.config file and from here we reach the rest of the configuration. Our configuration section is very simple.
[ConfigurationProperty(SourceIdentifier)] public Directories Source { get { return (Directories)this[SourceIdentifier]; } set { this[SourceIdentifier] = value; } }
[ConfigurationProperty(DestinationIdentifier)] public Directories Destination { get { return (Directories)this[DestinationIdentifier]; } set { this[SourceIdentifier] = value; } } }
Some test program to make sure that it works.
Console.WriteLine("SOURCE DIRECTORIES"); foreach (Directory directory in configuration.Source) { Console.WriteLine(directory.Path); }
Console.WriteLine("DESTINATION DIRECTORIES"); foreach (Directory directory in configuration.Destination) { Console.WriteLine(directory.Path); }
Console.ReadLine(); }
You can download the code sample as a zip archive from here.