我想在app.config
文件中添加自定义配置部分。
有没有办法做到这一点,如何在我的程序中访问这些设置。
以下是我要添加到app.config
的配置部分:
<RegisterCompanies>
<Companies>
<Company name="Tata Motors" code="Tata"/>
<Company name="Honda Motors" code="Honda"/>
</Companies>
</RegisterCompanies>
答案 0 :(得分:138)
创建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;
}
}
和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>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
然后用
加载配置var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
答案 1 :(得分:9)
你应该在CodeProject上查看Jon Rista关于.NET 2.0配置的三部分系列文章。
强烈推荐,写得很好,非常有帮助!
它非常清楚地向您展示了如何编写必要的类(从ConfigurationElement
和/或ConfigurationSection
派生)以设计您需要的自定义配置部分。