How to use ConfigurationManager.AppSettings with a custom section?

GibboK picture GibboK · Nov 25, 2013 · Viewed 44k times · Source

I need to get "http://example.com" from using App.config file.

But at the moment I am using:

string peopleXMLPath = ConfigurationManager.AppSettings["server"];

I cannot get the value.

Could you point out what I am doing wrong?

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <configSections>
    <section name="device" type="System.Configuration.SingleTagSectionHandler" />
    <section name="server" type="System.Configuration.SingleTagSectionHandler" />
  </configSections>
  <device id="1" description="petras room" location="" mall="" />
  <server url="http://example.com" />
</configuration>

Answer

Chris Mantle picture Chris Mantle · Nov 25, 2013

I think you need to get the config section, and access that:

var section = ConfigurationManager.GetSection("server") as NameValueCollection;
var value = section["url"];

And you also need to update your config file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <configSections>
    <section name="device" type="System.Configuration.NameValueSectionHandler" />
    <section name="server" type="System.Configuration.NameValueSectionHandler" />
  </configSections>
  <device>
    <add key="id" value="1" />
    <add key="description" value="petras room" />
    <add key="location" value="" />
    <add key="mall" value="" />
  </device>
  <server>
    <add key="url" value="http://example.com" />
  </server>
</configuration>

Edit: As CodeCaster mentioned in his answer, SingleTagSectionHandler is for internal use only. I think NameValueSectionHandler is the preferred way to define config sections.