Read Web.Config ConnectionString AppSettings
In web or windows forms application we need to Read Write ConnectionString Or AppSettings from Web.Config/App.Config file In Asp.Net to connect to Sql Server database.
This post explains How to Write Or Read Connection Information From configuration file for DB driven Applications.
We can either use connectionStrings section or AppSettings and can Write Programmatically At Run Time as well.
Sql Server information is usually written inside <configuration>
Where Data Source is db Server Address, Initial Catalog is DataBase Name
To use Windows Authentication instead of Sql Server Authentication write
For database attached in App_Data Folder we can write
USING APPSETTINGS
We can also write data in Key Value pairs.
READING WEB.CONFIG FILE PROGRAMMATICALLY
We can write code as mentioned below.
C# CODE
VB.NET CODE
This post explains How to Write Or Read Connection Information From configuration file for DB driven Applications.
We can either use connectionStrings section or AppSettings and can Write Programmatically At Run Time as well.
Sql Server information is usually written inside <configuration>
1: <configuration>
2: <connectionStrings>
3:
4: <add name="MyCon"
5: connectionString="Data Source=AMITJAIN\SQL;
6: Initial Catalog=Northwind;User ID=amit;Password=password"
7: providerName="System.Data.SqlClient" />
8:
9: </connectionStrings>
10: </configuration>
Where Data Source is db Server Address, Initial Catalog is DataBase Name
To use Windows Authentication instead of Sql Server Authentication write
1: <connectionStrings>
2:
3: <add name="MyCon"
4: connectionString="Data Source=AMITJAIN\SQL;
5: Initial Catalog=Northwind;Integrated Security=True"
6: providerName="System.Data.SqlClient" />
7:
8: </connectionStrings>
For database attached in App_Data Folder we can write
1: <connectionStrings>
2:
3: <add name="con"
4: connectionString="Data Source=.\SQLEXPRESS;
5: AttachDbFilename=|DataDirectory|\NORTHWND.MDF;
6: Integrated Security=True;User Instance=True"
7: providerName="System.Data.SqlClient" />
8:
9: </connectionStrings>
USING APPSETTINGS
We can also write data in Key Value pairs.
1: <configuration>
2: <appSettings>
3: <add key="con"
4: value="Data Source=AMITJAIN\SQL;
5: Initial Catalog=Northwind;
6: User ID=amit;Password=password"/>
7: </appSettings>
8: </configuration>
READING WEB.CONFIG FILE PROGRAMMATICALLY
We can write code as mentioned below.
C# CODE
1
using
System.Configuration;
2
string
strConn = ConfigurationManager.ConnectionStrings[
"MyCon"
].ConnectionString;
1
using
System.Configuration;
2
string
strConn = ConfigurationManager.AppSettings[
"con"
].ToString();
VB.NET CODE
1
Imports
System.Configuration
2
Dim
strConn
As
String
= ConfigurationManager.ConnectionStrings(
"MyCon"
).ConnectionString
3
4
Dim
strConn
As
String
= ConfigurationManager.AppSettings(
"con"
).ToString()
0 comments: