自定义配置部分,我想添加自定义configsection在app.config文件如下如何创建的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
@Sjoerd,通过将它们放在单独的配置文件中达到什么目的?这些条目应该全部在一个文件中,因为它们是相关的。 – Bhaskar
@Geeta,在你上面的代码中,我看到了这个 - “ConfigurationManager.GetSection(”RegisterCompanies“)' - 在你的配置文件中声明的RegisterCompanies部分在哪里?根据您之前发布的内容,我只能看到
Bhaskar