This article I have mostly copy / pasted from
here.
Here I've already explained how to create custom section in App.config, but now I need more complicated stuff, I need to have more attributes then just key / value pair.
Here is the example:
using System;
using System.Collections.Specialized;
using System.Configuration;
namespace CustomConfig
{
class Program
{
static void Main(string[] args)
{
MilosevBlogConfig links = (MilosevBlogConfig)ConfigurationManager.GetSection("milosev.com");
string homePage = ConfigurationManager.AppSettings.Get("homePage");
Console.WriteLine("Home page: " + homePage);
foreach (MilosevBlogCategoriesElement link in links.MilosevBlogInstances)
{
Console.WriteLine("Blog category: " + link.BlogCategory);
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
public class MilosevBlogCategoriesElement : ConfigurationElement
{
[ConfigurationProperty("BlogCategory", IsKey = true, IsRequired = true)]
public string BlogCategory
{
get
{
return (string)base["BlogCategory"];
}
set
{
base["BlogCategory"] = value;
}
}
}
public class MilosevBlogCategoriesElementCollection : ConfigurationElementCollection
{
public MilosevBlogCategoriesElement this[int index]
{
get
{
return (MilosevBlogCategoriesElement)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
BaseRemoveAt(index);
BaseAdd(index, value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new MilosevBlogCategoriesElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((MilosevBlogCategoriesElement)element).BlogCategory;
}
}
public class MilosevBlogConfig : ConfigurationSection
{
[ConfigurationProperty("categories")]
[ConfigurationCollection(typeof(MilosevBlogCategoriesElementCollection))]
public MilosevBlogCategoriesElementCollection MilosevBlogInstances
{
get
{
return (MilosevBlogCategoriesElementCollection)this["categories"];
}
}
}
}
App.config should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="milosev.com" type="CustomConfig.MilosevBlogConfig, CustomConfig"></section>
</configSections>
<milosev.com>
<categories>
<add BlogCategory="csharp"/>
<add BlogCategory="asp.net MVC"/>
</categories>
</milosev.com>
<appSettings>
<add key="homePage" value="http://milosev.com/" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
POI in App.config:
<configSections>
<section name="milosev.com" type="CustomConfig.MilosevBlogConfig, CustomConfig"></section>
</configSections>
Where MilosevBlogConfig looks like:
public class MilosevBlogConfig : ConfigurationSection
{
[ConfigurationProperty("categories")]
[ConfigurationCollection(typeof(MilosevBlogCategoriesElementCollection))]
public MilosevBlogCategoriesElementCollection MilosevBlogInstances
{
get
{
return (MilosevBlogCategoriesElementCollection)this["categories"];
}
}
}
Source code you can download from
here.