2011-09-20 14 views
2

自定义配置部分,我想添加自定义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; } } 
    } 
+0

考虑将这些设置放在单独的XML文件中,而不是放在app.config中。 – Sjoerd

+0

@Sjoerd,通过将它们放在单独的配置文件中达到什么目的?这些条目应该全部在一个文件中,因为它们是相关的。 – Bhaskar

+0

@Geeta,在你上面的代码中,我看到了这个 - “ConfigurationManager.GetSection(”RegisterCompanies“)' - 在你的配置文件中声明的RegisterCompanies部分在哪里?根据您之前发布的内容,我只能看到

Bhaskar

回答

-1
+0

我刚刚尝试了一个简单的例子,这是在一个网站中提到的。每当我做ConfigurationManager.GetSection(“公司”)它的返回null.Can任何人都可以告诉我什么是确切的问题。 – Geeta

+0

@Geeta,你需要为我显示你的配置文件来指出确切的问题。 – Bhaskar

+0

请找到配置文件内容<?xml version =“1.0”encoding =“utf-8”?>

<公司名称= “塔塔汽车” 代码= “塔塔”/> <公司名称= “本田汽车” 代码= “本田”/> Geeta

0

我将我的所有配置管理代码都放在我收集的类here上。这是一个example,这里有一些documentation。请注意,这是我个人从博客文章重新构建的代码,不再可以在线获得。

+0

我已经通过你的代码。但是你已经定义了你自己的类来处理像ConfigElementCollectionBase这样的集合。但是我想使用配置集合元素来完成它。如果你知道你能告诉我如何编写上述部分的代码ConfigurationElementCollection中。 – Geeta