Home » ASP.Net, Tech Corner

ConfigurationManager Class and the use of web.config file

7 October 2009 No Comments Posted By:Vivek

Some of the values and strings,for example the connection string, are used across all the pages of a website. Now to hard code this in each of the pages where it is needed is a tedious process as a change has to be updated in each of them.So what we do is to make use of the web.config file in the application to store these values.

There are two methods to store the connection string or any other value in the web.config file.Either you can add a key and value pair inside the <appSetting> element or make a custom section of your own in the web.config.To retrieve the values in the custom section defined,ASP.NET 2.0 provides you with the ConfigurationManager Class.

Let’s see both the methods of defining a connection string.
First in the <appSetting> element

<appSettings>
<add key="connectionString" value="connection string value" />
</appSettings>

Now to retrieve this,we can use the following code in the application

string strConn=ConfigurationSettings.AppSettings("connectionString");
SqlConnection conn=new SqlConnection(strconn);

Here the connection string is stored as key and value pair in the <appSettings> element of the web.config file.

Instead of using the <appSettings> section you can also add your own sections in the web.config file to have all your string value that you will be using in your application.
ASP.Net 2.0 provides with a special class for retrieving those customized string values. This class is called the ConfigurationManager class.

Now here we are using a custom section to store the connection string

Now to use the ConnectionStrings section of the web.config file, you can use code like

ConfigurationManager.ConnectionStrings["connection_name"].ConnectionString

The namespace to be added is System.Configuration

Here is another use of the class.

In the web.config,you add the following code,which gives an URL,which is used in many files and may change in the future.

<appSettings>
<add key="URL" value="http://www.three2tango.com/"/>
</appSettings>

Nowto use it  ,you can make use of the ConfigurationManager class

string URL=ConfigurationManager.AppSettings.Get("URL");

Related posts:

  1. How to Bind Images from Database in a GridView
  2. .NET Interview Questions & Answers
  3. .Net Framework 4.0 -New Features in Core Services
  4. XML serialization of Objects in .NET
  5. Convert a String in CSV format to INT Array in .NET

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>