如何在app.config中创build自定义configuration部分?

我想在我的app.config文件中添加一个自定义的configuration部分。 有没有办法做到这一点,我怎样才能访问我的程序中的这些设置。 以下是我想添加到我的app.config的configuration部分:

 <RegisterCompanies> <Companies> <Company name="Tata Motors" code="Tata"/> <Company name="Honda Motors" code="Honda"/> </Companies> </RegisterCompanies> 

创buildConfigurationElement公司:

 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; } } 

和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 ; } } } 

而且还必须在web.config(app.config)中注册新的configuration部分:

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

然后你加载你的configuration

 var config = RegisterCompaniesConfig.GetConfig(); foreach(var item in config.Companies) { do something .. } 

你应该在CodeProject上看看Jon Rista关于.NET 2.0configuration的三部分系列。

  • 解开.NET 2.0configuration的奥秘
  • 解码.NET 2.0configuration的奥秘
  • 破解.NET 2.0configuration的奥秘

强烈推荐,写得很好,非常有帮助!

它非常清楚地向您显示如何编写必要的类(从ConfigurationElement和/或ConfigurationSection派生),以devise您需要的自定义configuration节。