97

I want to add a custom configuration section in my app.config file. Is there a way to do it and how can I access these settings in my program. Following is the config section I want to add to my app.config:

<RegisterCompanies>
    <Companies>
      <Company name="Tata Motors" code="Tata"/>
      <Company name="Honda Motors" code="Honda"/>
    </Companies>
</RegisterCompanies>
John Smith
  • 7,243
  • 6
  • 49
  • 61
Embedd_0913
  • 16,125
  • 37
  • 97
  • 135

1 Answers1

156

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

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

ConfigurationElementCollection:

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

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablaNameSpace.RegisterCompaniesConfig, blablaAssemblyName" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}
Demodave
  • 6,242
  • 6
  • 43
  • 58
Jan Remunda
  • 7,840
  • 8
  • 51
  • 60
  • 24
    Its worth noting that if you are using an MVC app, then the section listed is fine. With a console app, Web Service, and perhaps others, you need to have ', AssemblyName' after 'blablabla.RegisterCompaniesConfig' – KevinDeus Nov 21 '13 at 09:15
  • Need to specify the assembly in the type attribute of the section tag – ilmatte Sep 01 '14 at 14:42
  • I'm getting the exception "does not inherit from 'System.Configuration.IConfigurationSectionHandler" .. what am I doing wrong ? – Oysio Mar 23 '15 at 10:35
  • Thank you @ilmatte. i missed out the assemble name – demo.b Jun 28 '15 at 23:47
  • 11
    Never ceases to amaze me how often Stackoverflow ranks higher than the [vendor's own documentation site](https://msdn.microsoft.com/en-us/library/2tw134k3.aspx) itself :) – Matt Borja Oct 30 '15 at 18:24
  • Guess I should've qualified my previous comment with the keywords I was actually using: `writing customconfig section c#` – Matt Borja Oct 30 '15 at 18:32
  • @KevinDeus can you show an example? – Thomas Aug 12 '16 at 19:23
  • 2
    Also worth noting for the uninitiated, NEEDS to be the first child of – JamieS Sep 22 '16 at 17:21
  • more details on the config file xml schema can be found [here](https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/section-element) – sscheider Apr 19 '19 at 18:08
  • 2
    Make ConfigurationElementCollection Type-Explicit: https://www.codeproject.com/Tips/1037705/Make-Your-ConfigurationElementCollection-Type-Expl – Kreol Jul 15 '19 at 15:19
  • It would be overkill for the original example, but Kreol is onto something that could be used for others with complex config files. I had done this before with nested collection classes, collection classes with indexers, typed item classes, typed values i.e. string, int, enum values, etc. You can basically make your config anyway you want and provide typed results when you go to retrieve it. But it can take a bit of effort at times. – stymie2 Feb 08 '22 at 19:34