In this article I will explain with an example, how to set and read
SQL Server Connection String for
SQL Server Authentication in
Web.Config file in
ASP.Net using C# and VB.Net.
In ASP.Net Web Applications, one has to reference the
System.Configuration Assembly in order to read the
SQL Server Connection String for Server Authentication from the
ConnectionStrings section of the
Web.Config file.
SQL Server Connection String for SQL Server Authentication in Web.Config file
Data Source - The name of the
SQL Server and its Instance.
Initial Catalog - The name of the Database.
<configuration>
<connectionStrings>
<add name= "ConString" connectionString= "Data Source=.\SQL2019;Initial Catalog=Northwind;User ID=sa;Password=pass1234"/>
</connectionStrings>
</configuration>
Adding System.Configuration reference
In order to access the
SQL Server Connection String for
Windows Authentication from
Web.Config file in code behind, the reference of the
System.Configuration Assembly is added to the project in the following way.
1. Right click on the project and click Add Reference option from the Context Menu.
2. From the Add Reference dialog box, click on .Net Tab and look for System.Configuration assembly. Once you find it simply select and click OK.
3. Once the reference is added, it will be shown in the References folder of the Solution Explorer.
Namespaces
You will need to import the following namespace.
C#
using System.Configuration;
VB.Net
Imports System.Configuration
Reading ConnectionString from Web.Config file in ASP.Net using C# and VB.Net
Once the reference is added, you can read the
SQL Server Connection String for
Windows Authentication from the
Web.Config file in the following way.
C#
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
VB.Net
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString