2014/07/07

Read collection from configuration file app.config in C#

App.config:
<configuration>
<configSections>
<section name="testConfig" type="Testy.ItemsConfigurationSection, Testy" />
</configSections>
<testConfig>
<items>
<item name="One" />
<item name="Two" />
</items>
</testConfig>
</configuration>
Service classes:
namespace Testy
{
public class ItemConfigurationElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
}
}
[ConfigurationCollection(typeof(ItemConfigurationElement), AddItemName = "item")]
public class ItemsConfigurationElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new ItemConfigurationElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ItemConfigurationElement)element).Name;
}
}
public class ItemsConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("items", IsDefaultCollection = true)]
public ItemsConfigurationElementCollection Tests
{
get { return (ItemsConfigurationElementCollection)this["items"]; }
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub
Usage:
try
{
ItemsConfigurationSection configManager = (ItemsConfigurationSection)ConfigurationManager.GetSection("testConfig");
var zmienna = configManager.Tests;
}
catch (Exception ex)
{
throw;
}
view raw gistfile1.cs hosted with ❤ by GitHub

No comments:

Post a Comment