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

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

问题描述

我想在app.config文件中添加自定义的configsection如下

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>

在部门部分,它指的是项目部分.

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

推荐答案

您应该在 CodeProject 上查看 Jon Rista 关于 .NET 2.0 配置的三部分系列.

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

强烈推荐,写得很好,非常有帮助!我从那些优秀的文章中学会了如何处理自定义配置部分.

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天全站免登陆