Get ConnectionString From Web.Config File ASP.Net

Get ConnectionString From Web.Config File ASP.Net

In this asp.net post i will explain you how to get or read connectionstring from web.config file in asp.net using c# and vb.net.

We can write out connectionstring string in web.config file as following two ways..

1. Write connectionstring inside  <ConnectionString> </ConnectionString>  tag.
2. Write conectionstring inside <appSettings></appSettings> tag

First way to write connectionstrin inside <ConnectionString> tag in we.config:

Write connectionstring inside ConnectionString tag inWeb.Config file.

<connectionStrings>
  <add name="MySQLConnection" providerName="System.Data.SqlClient"
  connectionString="Data Source=ServerName;Integrated Security=true;Initial Catalog=DatabaseName"/>
</connectionStrings>

We can read conectionstring from web.config file using System.Configuration. First imports System.Configuration namespace for read connectionstring from web.config file.

Read ConnectionString using C# from web.config.

protected void Page_Load(object sender, EventArgs e)
{
    string conn = System.Configuration.ConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString;
}

 Read ConnectionString using VB.Net from web.config.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim conn As String = System.Configuration.ConfigurationManager.ConnectionStrings("MySQLConnection").ConnectionString
End Sub

Now. let’s understand second way to read connectionstring from web.config file.

Write connectionstring inside appSettings tag inWeb.Config file.

<appSettings>
  <add key="MySQLConnection" value="Data Source=ServerName;Integrated Security=true;Initial Catalog=DatabaseName" />
</appSettings>

Read ConnectionString using C# from web.config.

protected void Page_Load(object sender, EventArgs e)
{
   string conn = System.Configuration.ConfigurationManager.AppSettings["MySQLConnection"];
}

 Read ConnectionString using VB.Net from web.config.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim conn As String = System.Configuration.ConfigurationManager.AppSettings("MySQLConnection")
End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *