ConfigurationManager Class and the use of web.config file
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:








Leave your response!