Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Config section in App.config C#


I'm a quite beginner with config sections in c#
I want to create a custom section in config file. What I've tried after googling is as the follows
Config file:

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="MyCustomSections">
      <section name="CustomSection" type="CustomSectionTest.CustomSection,CustomSection"/>
    </sectionGroup>
  </configSections>

  <MyCustomSections>
    <CustomSection key="Default"/>
  </MyCustomSections>
</configuration>


CustomSection.cs

    namespace CustomSectionTest
{
    public class CustomSection : ConfigurationSection
    {
        [ConfigurationProperty("key", DefaultValue="Default", IsRequired = true)]
        [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
        public String Key
        {
            get { return this["key"].ToString(); }
            set { this["key"] = value; }
        }
    }
}


When I use this code to retrieve Section I get an error saying configuration error.

var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("CustomSection");


What am I missing?
Thanks.

Edit
What I need ultimately is

    <CustomConfigSettings>
    <Setting id="1">
        <add key="Name" value="N"/>
        <add key="Type" value="D"/>
    </Setting>
    <Setting id="2">
        <add key="Name" value="O"/>
        <add key="Type" value="E"/>
    </Setting>
    <Setting id="3">
        <add key="Name" value="P"/>
        <add key="Type" value="F"/>
    </Setting>
</CustomConfigSettings>
like image 565
Chaturvedi Dewashish Avatar asked Oct 13 '12 22:10

Chaturvedi Dewashish


2 Answers

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="customAppSettingsGroup">
      <section name="customAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </sectionGroup>
  </configSections>
  <customAppSettingsGroup>
    <customAppSettings>
      <add key="KeyOne" value="ValueOne"/>
      <add key="KeyTwo" value="ValueTwo"/>
    </customAppSettings>
  </customAppSettingsGroup>
</configuration>

Usage:

NameValueCollection settings =  
   ConfigurationManager.GetSection("customAppSettingsGroup/customAppSettings")
   as System.Collections.Specialized.NameValueCollection;

if (settings != null)
{
 foreach (string key in settings.AllKeys)
 {
  Response.Write(key + ": " + settings[key] + "<br />");
 }
}
like image 71
Nesim Razon Avatar answered Sep 28 '22 09:09

Nesim Razon


Try using:

var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("MyCustomSections/CustomSection");

You need both the name of the section group and the custom section.

like image 36
JG in SD Avatar answered Sep 28 '22 10:09

JG in SD