关于c#4.0:如何在app.config中创建自定义配置节

How to create custom config section in app.config

我想在app.config文件中添加自定义配置部分,如下所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<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:请找到你的评论代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 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; } }
    }


You should check out乔恩S系列三部分rista' codeproject上出现Configuration 2.0在线在线。P></

  • unraveling configuration of the秘密出现2.0
  • configuration of the秘密解码出现2.0
  • configuration of the秘密出现2.0裂纹

深圳好的建议和帮助,非常好!我的经验与海关,how to新政从那些优秀的文章配置形截面。P></


这些基本的管理队列的Configuration类here on the文集。This is an example,和有一些文件。that this is personally已知代码的重构,从博客在线,不可用任何更多。P></


这将帮助你msdn.microsoft.com http:/ / / /图书馆/销售额2tw134k3(V = .aspx vs.80)P></