开发者

How to create custom config section in 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>

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: 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 : C开发者_如何学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 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.


I base all my configuration management code on the classes I collected here. This is an example, and here's some documentation. Note that this is code I personally refactored from a blog post that isn't available on-line any more.


This will help you http://msdn.microsoft.com/en-us/library/2tw134k3(v=vs.80).aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜