How to create custom config section in app.config?
本问题已经有最佳答案,请猛点这里访问。
我想在我的
1 2 3 4 5 6 | <RegisterCompanies> <Companies> <Company name="Tata Motors" code="Tata"/> <Company name="Honda Motors" code="Honda"/> </Companies> </RegisterCompanies> |
创建配置元素公司:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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; } } } |
配置元素集合:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 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; } } |
和配置部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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)中注册新的配置部分:
1 2 3 | <configuration> <configSections> <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..> |
然后加载配置
1 2 3 4 5 | var config = RegisterCompaniesConfig.GetConfig(); foreach(var item in config.Companies) { do something .. } |
您应该在codeproject上查看jon rista的.net 2.0配置上的三部分系列。
- 揭开.NET 2.0配置的神秘面纱
- 解码.NET 2.0配置的奥秘
- 破解.NET 2.0配置的奥秘
强烈推荐,写得好,非常有用!
它向您清楚地展示了如何编写必要的类(从