Wednesday, May 9, 2012

Read/write appsettings from web config.file in c#.


Introduction: 

In this Post I will explain how to read or write appsettings in web.config file using asp.net.

Description: 

Now I will explain how to write appsettings in web.config file and how to read appsettings from web.config file using asp.net. 


To add appsettings first create new website open web.config file and search for “appSettings” and add new item in appSettings section.The section is like this.

<appSettings>
<add key="yourappsettingsstringName" value=" yourappsettingsvalue" />
</appSettings>

The main purpose used for appsettings is for declaring the connection string.because if we have a too many pages in application then it will not require to write connection string on every page.However we can define any key which are used in many pages.

Example of declaring 
appSettings in web.config file like this.

<appSettings>
<add key="dbconnectionstring" value="Data SOurce=KartikPatel;Initial Catalog=MysampleDB; Integrated Security=true"/>
</appSettings>


The good advantage of writing the appsettings in web config is we can manage it easily.means if we want to change its value then we can change it only in appsetting.we dont need to write and change it in every pages.This is the biggest advantage of it.

Lets take an Example.and test it.


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Read or Write appsetting values from web.config file in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblText" runat="server"/>
</div>
</form>
</body>
</html>

After that add following namespace in codebehind file

using System;
using System.Configuration;

 The namespace using System.Configuration; is used to get configuration section details from web.config file.

After add namespaces write the following code in code behind

protected void Page_Load(object sender, EventArgs e)
{
//Get appsettings string value from web.config file
string strcon = System.Configuration.ConfigurationManager.AppSettings["dbconnectionstring"];
//Bind appsettings string value to label
lblText.Text = strcon;
}

Above Example shows how to read the appsettings from web config.

0 comments:

Post a Comment