How to access a variable from the web.config file using C#

The web.config file can be a handy place to put site wide settings like the website name or contact admin email address. The steps below will let you use your web.config file to store and retrieve those details. This example will show you how to set the website name in the web.config, create a class to access that name and display the name in page title.

First up we need to store the values in the web.config file itself so open up your web.config file in your project and locate the <appSettings /> tag. You want your appSettings element to look something like this:

<appSettings>
    <add key="SiteName" value="My New Site" />
 </appSettings>

So now you have the name for your site set in the web.config. But how do we actually get this information into our pages? Well the good news is that it's quite easy! I'm going to make a new class called 'sitesettings.cs' in my App_Code folder and inside in that put the following code:

using System;
using System.Collections.Generic;
using System.Web;
//this will allow you to pickup the web.config values
using System.Web.Configuration;
/// 
/// Gets the website settings stored in the web.config file
/// 
public class WebsiteSettings
{
public WebsiteSettings()
{
}
//get the web site title
public static string SiteTitle
{
get
{
return WebConfigurationManager.AppSettings["SiteName"];
}
}
}

Once you have the code above saved as a new class you can access the values within your .cs pages with ease. For example, if you want to print out the website name as a page title you simple need to include the following line in your code behind page (this example is for an aspx page that uses a MasterPage):

protected void Page_Load(object sender, EventArgs e)
{
//line below will read the site name from webconfig
//and display "My New Site - home page" in your browser window title
Master.Page.Title = WebsiteSettings.SiteTitle + " - home page";
}

Obviously this is only a quick example of what you can do but it can be a handy way to store some of your site settings like the site name, url links, admin email address, etc.

blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets