I'm sure this should be easy, but it's taken me most of a
morning of reading MSDN and tweaking code to get it to work. Most
of the documentation that I have found has either been massively
out of context, showing small segments of code and not explaining
where it fits in or what it does; or it's been hugely over
complicated, showing complete examples with masses of boilerplate
code.
I've been trying to get a simple collection, using
<AddElement> tags to add a list of items, similar to how
AppSettings and ConnectionStrings sections work. It was extremely
easy to create a custom configuration section,
with a single item and associated properties - creating a
collection of items, with add/remove/clear
functionality appeared to be a different matter.
Turns out, it's actually not that difficult. 3 classes, 2
overrides, and some properties. After that, it's just a case of
registering the custom section in the configuration
file in the <configSections> section.
Section class
The section class inherits from ConfigurationSection, and serves
as the wrapper for your configuration section in the app.config
file. This is what you'll add to the <configSections>
attribute to register the type in the Configuration manager:
public class ElementSection : ConfigurationSection
{
[ConfigurationProperty("Elements", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(Elements), AddItemName = "AddElement", ClearItemsName = "ClearElements", RemoveItemName = "RemoveElement")]
public Elements Elements
{ get { return this["Elements"] as Elements; } }
}
Collection class
The collection class is required to tell the Configuration
manager what to create and what to use to retrieve the elements.
There are 2 required overrides for this class:
public class Elements : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new Element();
}
protected override object GetElementKey(ConfigurationElement element)
{
return (element as Element).Name;
}
}
Element class
The class that contains your actual elements, all that's
required here is a property for each value you want to store
against the element, which needs to be decorated with the
ConfigurationProperty attribute.
public class Element : ConfigurationElement
{
[ConfigurationProperty("Name", IsRequired = true)]
public string Name
{
get { return (string) this["Name"]; }
set { this["Name"] = value; }
}
}
app.config registration
The app.config file registration should be
fairly trivial, all that's required is the name you want to give
the section, the namespace and class name, and the assembly
name:
<configuration>
<configSections>
<section name="ElementSection"
type="namespace.ElementSection, AssemblyName />
</configSections>
</configuration>
And that's all there is to it. If anything is not clear, drop a
comment and I'll try to clarify.