如何在app.config中创建自定义配置节?
问题描述:
我想在我的app.config
文件中添加自定义配置部分。 有没有办法做到这一点,我怎样才能在我的程序中访问这些设置。 以下是配置节我要添加到我的app.config
:如何在app.config中创建自定义配置节?
<RegisterCompanies>
<Companies>
<Company name="Tata Motors" code="Tata"/>
<Company name="Honda Motors" code="Honda"/>
</Companies>
</RegisterCompanies>
答
创建的ConfigurationElement公司:
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;
}
}
和配置节:
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中(新的配置部分的应用程序。配置):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
然后你
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
答
你应该检查乔恩Rista的三部系列在.NET 2.0配置了CodeProject上。
- Unraveling the mysteries of .NET 2.0 configuration
- Decoding the mysteries of .NET 2.0 configuration
- Cracking the mysteries of .NET 2.0 configuration
强烈推荐,写得很好,非常有帮助!
它非常清楚地向您显示如何编写必要的类(从ConfigurationElement
和/或ConfigurationSection
派生),以设计您需要的自定义配置节。
其值得注意的是,如果你使用的是MVC应用程序,然后列出的部分是好的加载你的配置。使用控制台应用程序,Web服务以及其他方法,您需要在'blablabla.RegisterCompaniesConfig'后面有',AssemblyName' – KevinDeus 2013-11-21 09:15:47
需要在节标记的type属性中指定程序集 – ilmatte 2014-09-01 14:42:10
我收到异常“不继承自“System.Configuration.IConfigurationSectionHandler”..我做错了什么? – Oysio 2015-03-23 10:35:05