sub appsettings in the appsetting node c#

You can add custom sections in app.config without writing additional code. All you have to do is “declaring” new section in configSections node like that

<configSections>
      <section name="genericAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>

and then you can define this section filling it with keys and values:

  <genericAppSettings>
      <add key="testkey" value="generic" />
      <add key="another" value="testvalue" />
  </genericAppSettings>

To get value of a key from this section you have to add System.Configuration dll as reference to your project, add using and use GetSection method. Example:

using System.Collections.Specialized;
using System.Configuration;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            NameValueCollection test = (NameValueCollection)ConfigurationManager.GetSection("genericAppSettings");

            string a = test["another"];
        }
    }
}

Nice thing is that you can easily make groups of sections if you need this:

<configSections>
    <sectionGroup name="customAppSettingsGroup">
      <section name="genericAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
 // another sections
    </sectionGroup>
</configSections>

  <customAppSettingsGroup>
    <genericAppSettings>
      <add key="testkey" value="generic" />
      <add key="another" value="testvalue" />
    </genericAppSettings>
    // another sections
  </customAppSettingsGroup>

If you use groups, to access sections you have to access them using {group name}/{section name} format:

NameValueCollection test = (NameValueCollection)ConfigurationManager.GetSection("customAppSettingsGroup/genericAppSettings");

Leave a Comment