Click here to Skip to main content
15,892,005 members
Articles / Programming Languages / C#

Read web.config Settings

Rate me:
Please Sign up or sign in to vote.
4.80/5 (5 votes)
23 Jul 2015CPOL 50.6K   5   9   2
Read web.config Settings

I don’t know about you, but I always forget how to read settings from web.config file. So, I wrote a static class that will help me with that and I’d like to share it with you.

1. Read Connection Strings

C#
public static string GetConnectionStringUsingConfigurationManager(string nameOfConnectionString)
{
    return System.Configuration.ConfigurationManager.ConnectionStrings[nameOfConnectionString].ToString();
}

public static string GetConnectionString(string nameOfConnectionString)
{
    //null indicates default web.config
    //you can set it to what ever config file in you need
    System.Configuration.Configuration config =
        System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
    if (config.ConnectionStrings.ConnectionStrings.Count > 0)
    {
        var connString = config.ConnectionStrings.ConnectionStrings[nameOfConnectionString].ToString();
        return connString;
    }
    return "";
}

Here are two ways to read connection string from web.config file.

We could also modify GetConnectionString method to take another parameter filePath to use different XML file than default web.config.

2. Read App Settings

C#
public static string GetAppSettingUsingConfigurationManager(string customField)
{
    return System.Configuration.ConfigurationManager.AppSettings[customField];
}

public static string GetAppSetting(string customField)
{
    System.Configuration.Configuration config =
        System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
    if (config.AppSettings.Settings.Count > 0)
    {
        var customSetting = config.AppSettings.Settings[customField].ToString();
        if (!string.IsNullOrEmpty(customSetting))
        {
            return customSetting;
        }
    }
    return null;
}

appSettings is a key-value element in web.config file where we can store our own settings.

Example of appSettings:

XML
<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="DatabaseINILocation" value="C:\config\config.ini" />
    <add key="testPort" value="49610" />
</appSettings>

3. Read Section

C#
public static string ReadFieldFromSection(string sectionName, string field, string attribute)
{
    var section = (XmlElement)ConfigurationManager.GetSection(sectionName);
    if (section.GetElementsByTagName(field).Count > 0)
    {
        XmlElement element = (XmlElement) section.GetElementsByTagName(field).Item(0);
        var fieldValue = element.Attributes[attribute].Value;
        return fieldValue;
    }
    return null;
}

This code is very specific to sections that you want to read so you would have to probably modify it little bit.

Example of section that you can read with this code:

XML
<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="log/log.txt"/>
    <appendToFile value="true"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %level %logger - %message%newline%exception"/>
    </layout>
  </appender>
</log4net>

And finally, how can you call these methods from your code:

C#
ReadConfig.GetAppSetting("testPort");
ReadConfig.GetAppSettingUsingConfigurationManager("testPort");
ReadConfig.GetAppSettingUsingConfigurationManager("testPort");
ReadConfig.ReadFieldFromSection("log4net", "file", "value");
ReadConfig.GetConnectionString("TestDatabase");
ReadConfig.GetAppSettingUsingConfigurationManager("TestDatabase");

You can download the complete class here: ReadConfig.cs.

Hope it will help you.

This article was originally posted at http://codedreaming.com/read-web-config-settings

License

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


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

Comments and Discussions

 
QuestionEF Pin
mansimansi27-Jul-15 7:52
mansimansi27-Jul-15 7:52 
AnswerRe: EF Pin
xszaboj3-Aug-15 1:20
xszaboj3-Aug-15 1:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.