We can read the web.config file
explicitly by using XML Namespace.
<appSettings>
<add key="OracleConnection" value="Data Source=TORCL;User Id=myUsername;Password=myPassword;"/>
<add key="SqlServerConnection" value="Data Source=myServerAddress;Initial Catalog=myDataBase;User
Id=myUsername;Password=myPassword;"/>
</appSettings>
We can read this web.config by using
below code
Asp.net
2.0
string
connStr = ConfigurationSettings.AppSettings("OracleConnection");
Asp.net
3.0 and above
string
connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
But
sometime if you want to read the config file any other purpose then we
can use this code before use this code you need to include the following
namespaces
System.Configuration;
System.Web.Configuration;
System.Xml;
C#
string webconfigpath = string.Empty;
XmlDocument xdoc = new XmlDocument();
XmlNodeList xnodes;
string oracleconnetion = string.Empty;
string sqlconnection = string.Empty;
webconfigpath = GetWebconfigPath();
xdoc.Load(webconfigpath);
xnodes = xdoc.GetElementsByTagName("add");
foreach(XmlNode node in xnodes)
{
if (node.Attributes["key"].Value == "OracleConnection")
{
oracleconnetion= node.Attributes["value"].Value;
}
if (node.Attributes["key"].Value == "SqlServerConnection")
{
sqlconnection = node.Attributes["value"].Value;
}
}
/// <summary>
/// Get
Path of the Web.config File which is reside in server side
/// </summary>
/// <returns></returns>
public string GetWebconfigPath()
{
Configuration config ;
string path = string.Empty;
config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
path = config.FilePath;
return path;
}
VB
Dim xdoc As New XmlDocument
Dim webconfigpath As String
Dim nodes As XmlNodeList
Dim oracleconnetion As String = String.Empty
Dim sqlconnection As String = String.Empty
webconfigpath = GetReportLookupPath()
xdoc.Load(webconfigpath)
nodes = xdoc.GetElementsByTagName("add")
For Each xmlnode As XmlNode In nodes
If (xmlnode.Attributes("key").Value
= "OracleConnection") Then
oracleconnetion = xmlnode.Attributes("value").Value
End If
If (xmlnode.Attributes("key").Value
= "SqlServerConnection") Then
sqlconnection = xmlnode.Attributes("value").Value
End If
Next
''' <summary>
''' Get Path of the
Web.config File which is reside in server side
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function GetReportLookupPath() As String
Dim config As Configuration
Dim path As String
config = WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath)
path = config.FilePath
Return path
End Function
I
hope this article will be very helpful to all. Thanks for reading this article.
“Keep reading and share the knowledge”
“Grow more trees to save
Earth”