Using Web.Config in ASP.NET and ASP


Introduction: 

Web.config acts as a central location for storing the information to be accessed by web pages. This information could be a Connection String stored at a centralized location so that it can be accessed in a data-driven page. If the connection string changes its just a matter of changing it at one place.

In classic ASP such global information was typically stored as an application variable.

In the sample we'll read the information from web.config using ASP.NET and ASP as there could be a possibility of project having ASP and ASP.NET pages.

web.config:

Contains a key-value pair.
web.config

<?xml version="1.0" encoding="utf-8"?>
<
configuration>
<
appSettings>
<add key="ConnectionString1" value="server=localhost;uid=sa;pwd=;database=northwind" />
<add key="ConnectionString2" value="server=localhost;uid=sa;pwd=;database=pubs" />
</
appSettings>
</
configuration>

In ASP.NET: 

We can just using Configuration.AppSettings(<key>) gives the Value.(Namespace:System.Configuration)

VB.NET

Dim strConnection As String
strConnection = ConfigurationSettings.AppSettings("ConnectionString1")
Response.Write(strConnection)

C#

string strConnection;
strConnection = ConfigurationSettings.AppSettings["ConnectionString1"];
Response.Write(strConnection);

In ASP

We need to iterate through the nodes in web.config.

vbscript

set xmlDoc=server.CreateObject("Microsoft.XMLDOM")
set xmlappSettings=server.CreateObject("Microsoft.XMLDOM")
set xmladd=server.CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load(server.MapPath ("web.config"))
set xmlappSettings = xmldoc.GetElementsByTagName("appSettings").Item(0)
set xmladd = xmlappSettings.GetElementsByTagName("add")
for each x in xmladd
'Check for the Atrribute Value
if  x.getAttribute("key") ="ConnectionString1" then
Response.write(x.getAttribute("value"))
end if
next


Similar Articles