This post explains How to Write Or Read Connection String From ASP.NET Web Config 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>

<configuration>

<connectionStrings>  

<add name="MyCon"

  connectionString="Data Source=AMITJAIN\SQL;

  Initial Catalog=Northwind;User ID=amit;Password=password"

  providerName="System.Data.SqlClient" />  

</connectionStrings>

</configuration>


Where Data Source is db Server Address, Initial Catalog is DataBase Name. To use Windows Authentication instead of Sql Server Authentication write

  <connectionStrings>  

  <add name="MyCon"

  connectionString="Data Source=AMITJAIN\SQL;

  Initial Catalog=Northwind;Integrated Security=True"

  providerName="System.Data.SqlClient" />  

</connectionStrings>


For database attached in App_Data Folder we can write

<connectionStrings>  

  <add name="con"

  connectionString="Data Source=.\SQLEXPRESS;

  AttachDbFilename=|DataDirectory|\NORTHWND.MDF;

  Integrated Security=True;User Instance=True"

  providerName="System.Data.SqlClient" />  

</connectionStrings>


USING APPSETTINGS We can also write data in Key Value pairs.

  <configuration>

  <appSettings>

  <add key="con"

       value="Data Source=AMITJAIN\SQL;

              Initial Catalog=Northwind;

              User ID=amit;Password=password"/>

  </appSettings>

  </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()

Best ASP.NET 4.6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.