Saturday, January 3, 2009

Web Config file in ASP.net

How to add a web.config file?


1) Create a new website by selecting File->New->Website from the Menu

Visual Studio 2005 will create a basic website with a default page for you.

2) Click on the Website ->Add New Item from the menu or press Ctrl+Shift+A

A new pop up window will be displayed. Select Web Configuration File from the popUp.

3) Now you can see a Web.config file added to your project.

The default web.config file will look something like this.(I removed all the comments from web.config)


We can now use the web.config file. Now lets store a value in web.config file and read that from our application.

Reading a value from web.config.

1) Open web.config file


2) Add a new key in web.config file under AppSettings.

Now the web.config file will look like this.


3) Now We can read this value from our aspx page.

For reading a value from web.config file, we can use the ConfigurationManager class.

Write the following code in page load event .

String Name = ConfigurationManager.AppSettings.Get("Name");

Response.Write("Value of Name from web.config is : " + Name);


4) Now run your sample website. Done !


Storing a Connection String in web.config.


Storing your connection string in web.config file when you are using visual studion 2005 is very easy.

You can add a new connection string under the tag

Here is a sample web.config.

You can read the connection string using the following code.

String connectionString = ConfigurationManager.ConnectionStrings["TestConnectionString"].ToString();

Response.Write("Value of TestConnectionString from web.config is : " + connectionString);

No comments:

Post a Comment