Read ConnectionString AppSettings From Web.Config In Asp.Net

Read Write ConnectionString Or AppSettings From Web.Config/App.Config File In Asp.Net In web or windows forms application to connect to Sql Server database.

This post explains How to Write Or Read Connection String From Web 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
using System.Configuration;
string strConn = ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString;

using System.Configuration;
string strConn = ConfigurationManager.AppSettings["con"].ToString();

VB.NET CODE
Imports System.Configuration
Dim strConn As String = ConfigurationManager.ConnectionStrings("MyCon").ConnectionString

Dim strConn As String = ConfigurationManager.AppSettings("con").ToString()


If you like this post than join us or share

1 comments:

Indrajeet bhattacharya said...

Very good and to the point article. I liked it.

- Indrajeet


Find More Articles