【发布时间】:2011-11-21 01:20:23
【问题描述】:
我想在 app.config 文件中添加自定义配置部分,如下所示
<Companies>
<Company name="" code=""/>
<Company name="" code=""/>
</Companies>
<Employees>
<Employee name="" Des="" addr="" sal=""/>
<Employee name="" Des="" addr="" sal=""/>
</Employeess>
<Departments>
<Department Id="" Projects=""/>
</Departments>
<Projects>
<Project Path=""/>
</Projects>
在部门部分中,它指的是项目部分。
谁能告诉我怎么做?以及如何在我的代码中访问它?
@Bhaskar:请找到您评论的代码。
public class RegisterCompaniesConfig : ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies")?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
public Companies Companies
{
get
{
object o = this["Companies"]; return o as Companies;
}
}
}
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);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{ return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{ return ((Company)element).Name; }
}
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; } }
}
【问题讨论】:
-
考虑将这些设置放在单独的 XML 文件中,而不是 app.config 中。
-
@Sjoerd ,将它们放在单独的配置文件中可以实现什么?这些条目都应该在一个文件中,因为它们是相关的。
-
@Geeta,在您上面的代码中,我看到了这个-
ConfigurationManager.GetSection("RegisterCompanies")-您的配置文件中声明的RegisterCompanies部分在哪里?根据您之前发布的内容,我只能看到<section name="Companies"。
标签: c#-4.0 app-config