Reputation: 1082
I need to create a configuration section in the web.config file. The config section look like this.
<component name="name1" title="title1" description="description1"/>
<component name="name2" title="title2" description="description2"/>
<component name="name3" title="title3" description="description3"/>
How to create such a configuration setting and how can I access the attributes in the config in c# code.
Upvotes: 0
Views: 2308
Reputation: 5405
1) Create a class and inherit from ConfigurationSection
public class ComponentCustomSection : ConfigurationSection
2) Add properties and flag them with the ConfigurationProperty attribute
[ConfigurationProperty("name")]
public string Name
{
get { return ((string)this["name"]); }
}
[ConfigurationProperty("title")]
public string Title
{
get { return ((string)this["title"]); }
}
[ConfigurationProperty("description")]
public string Description
{
get { return ((string)this["description"]); }
}
3) Add the information of your custom config section in your config file (under the Configuration tag)
<configSections>
<section name="component" type="YourAssembly.ComponentCustomSection, YourAssembly"/>
</configSections>
4) You can get the section using the following code
var section = ConfigurationManager.GetSection("component")
Note that this would work with a single component tag.
If you need to have N tags, you should encapsulate them in a parent tag, like this
<components>
<component name="name1" title="title1" description="description1"/>
<component name="name2" title="title2" description="description2"/>
<component name="name3" title="title3" description="description3"/>
</components>
Here is a nice article to get you started on custom configuration sections
Here is a question about having a customSection with child elements that should help you
Upvotes: 3