How to create a custom configuration section in app.config?

I want to add a custom configuration section to my app.config file. Is there a way to do this and how can I access these settings in my program. The following is the configuration section that I want to add to my app.config :

 <RegisterCompanies> <Companies> <Company name="Tata Motors" code="Tata"/> <Company name="Honda Motors" code="Honda"/> </Companies> </RegisterCompanies> 
+86
c # app-config
Aug 22 '09 at 14:11
source share
2 answers

Import namespace:

 using System.Configuration; 

Creating a configuration Company element:

 public class Company : ConfigurationElement { [ConfigurationProperty("name", IsRequired = true)] public string Name { get { return this["name"] as string; } } [ConfigurationProperty("code", IsRequired = true)] public string Code { get { return this["code"] as string; } } } 

ConfigurationElementCollection:

 public class Companies : ConfigurationElementCollection { public Company this[int index] { get { return base.BaseGet(index) as Company ; } set { if (base.BaseGet(index) != null) { base.BaseRemoveAt(index); } this.BaseAdd(index, value); } } public new Company this[string responseString] { get { return (Company) BaseGet(responseString); } set { if(BaseGet(responseString) != null) { BaseRemoveAt(BaseIndexOf(BaseGet(responseString))); } BaseAdd(value); } } protected override System.Configuration.ConfigurationElement CreateNewElement() { return new Company(); } protected override object GetElementKey(System.Configuration.ConfigurationElement element) { return ((Company)element).Name; } } 

and ConfigurationSection:

 public class RegisterCompaniesConfig : ConfigurationSection { public static RegisterCompaniesConfig GetConfig() { return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig(); } [System.Configuration.ConfigurationProperty("Companies")] [ConfigurationCollection(typeof(Companies), AddItemName = "Company")] public Companies Companies { get { object o = this["Companies"]; return o as Companies ; } } } 

and you must also register a new configuration section in web.config (app.config):

 <configuration> <configSections> <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..> 

Then you load your config from

 var config = RegisterCompaniesConfig.GetConfig(); foreach(var item in config.Companies) { do something .. } 
+140
Aug 22 '09 at 14:24
source share

You should check out the three-part series of Jon Rista for the .NET 2.0 configuration on CodeProject.

Highly recommended, well written and very helpful!

This very clearly shows how to write the necessary classes (coming from ConfigurationElement and / or ConfigurationSection ) to create the necessary configuration sections.

+9
Aug 22 '09 at 14:15
source share



All Articles