Click here to Skip to main content
15,886,773 members
Articles / Web Development / ASP.NET
Tip/Trick

Read Sections from web.config Not Located in Root

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
23 Feb 2013CPOL 14.1K   7  
This tip explains how to keep application settings classified by sections in another config file.

Introduction

This tip explains how to keep application settings classified by sections in another config file.

Background

Putting too much application setting in web.config in root may make it hard to read. So those can be kept in additional config file classified with sections.

Using the Code

A web.config file can be added in any folder other than root. If you only wish to store settings not specific to the folder you are adding it to, it is better to add it in a separate folder, as web.config in sub folder overrides settings from root.

Web.config in a sample project is as follows:

XML
<?xml version="1.0"?>
<configuration>
  <configSections>
    <!--The following code declares a section group called Group1. -->
    <sectionGroup name="Group1">
      <section name="Section1"
       type="System.Configuration.NameValueSectionHandler" />
      <section name="Section2"
       type="System.Configuration.NameValueSectionHandler" />
    </sectionGroup>
  </configSections>

  <Group1>
    <Section1>
      <add key="Setting1" value="value1" />
      <add key="Setting2" value="value2" />
    </Section1>
    <Section2>
      <add key="Setting1" value="value12" />
      <add key="Setting2" value="value22" />
    </Section2>
  </Group1>
</configuration>  

Here, I have added to sections, Section1 and Section2, of type System.Configuration.NameValueSectionHandler to group Group1. Configurations of the same are added below.

These settings can be read from code as shown below:

C#
var Section1 = 
           (System.Collections.Specialized.NameValueCollection)
          WebConfigurationManager.GetSection("Group1/Section2",
          (System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "/MySettings"));
foreach (var key in Section1.AllKeys)
{
            Response.Write("Key : " + key + " Value : " + Section1[key] + "<br/>");
}  

History

  • Added: 21 Sept 2012

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Systems Engineer TCS
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --