The root element of a config file is the <configuration> element, which can have zero or more children. These child elements are known as configuration sections. Each config section in turn can also have zero or more child elements, which are known as configuration elements.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="Default" connectionString="Server=myServer;Database=myDB;" />
<add name="Backup" connectionString="Server=myBackupServer;Database=myDB;" />
</connectionStrings>
<appSettings>
<add key="RequireLogin" value="True" />
<add key="Timeout" value="10" />
</appSettings>
</configuration>
var def = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
var bak = ConfigurationManager.ConnectionStrings["Backup"].ConnectionString;
var requireLogin = ConfigurationManager.AppSettings["RequireLogin"]; // Returns "True"
var timeout = ConfigurationManager.AppSettings["Timeout"]; // Returns "10"
The <connectionStrings> and <appSettings> config sections are built-in. If you want to use a non-built in config sections, you need to explicitly register them. This is done in the <configSections> element in your config file.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="glimpse" type="Glimpse.Core.Configuration.Section, Glimpse.Core" />
</configSections>
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
<logging level="Trace" />
</glimpse>
</configuration>
Here we register a config section named "glimpse"
, implemented by the Glimpse.Core.Configuration.Section
type found in the Glimpse.Core
assembly. The name of the config section element must match the registered name, hence the <glimpse>
config section.
The <glimpse>
config section itself is interesting. Besides having the <logging>
child config element, it also has config options itself, expressed as attributes. This shows that there are two ways to define config options in a config section:
For simple configuration options, attributes on the config section element probably suffice. However, this has some disadvantages: