如何在app.config中创建自定义配置部分 [英] How to create custom config section in app.config

查看:132
本文介绍了如何在app.config中创建自定义配置部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add the custom configsection in the app.config file as follows

<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>

在Department部分,它指的是Projects部分。

In the Department section it is referring to Projects section.

有人可以告诉我怎么办吗?

Can anybody tell me way to do it? And how to access it in my code?

@Bhaskar:请找到您的意见的代码。

@Bhaskar: Please find the code for your comment.

 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; } }
    } 


推荐答案

Jon Rista在CodeProject上配置.NET 2.0的三部分系列。

You should check out Jon Rista's three-part series on .NET 2.0 configuration up on CodeProject.

  • Unraveling the mysteries of .NET 2.0 configuration
  • Decoding the mysteries of .NET 2.0 configuration
  • Cracking the mysteries of .NET 2.0 configuration

强烈推荐,写得很好,非常有帮助!我已经学会了如何处理这些优秀文章的自定义配置节。

Highly recommended, well written and extremely helpful! I've learned how to deal with custom config sections from those excellent articles.

这篇关于如何在app.config中创建自定义配置部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆