How To Read And Write Connection String In Web.Config?
Web.config file is recommended place for storing connection strings in ASP.NET web application.
To add connection string to web.config, you need to add new item in ConnectionStrings section. You can use XML code like this:
<configuration>
<connectionStrings>
<clear />
<add name="YourConnectionStringName" providerName="System.Data.SqlClient"
connectionString="server=(local); Initial Catalog=YourDatabaseName; uid=YourUserName; Password=SomeComplexPassword;" />
</connectionStrings>
</configuration>
When you have one or more connection strings in your web.config file, you can read them when needed with ASP.NET server side code.
[ C# ]
using System;
using System.Data.SqlClient;
// We need this namespace to access web.config file
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Receive connection string from web.config
string myConnStr = ConfigurationManager.ConnectionStrings
["YourConnectionStringName"].ConnectionString;
// Create new connection to database and open database
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = myConnStr; // Set connection string
myConn.Open();
 }
}
[ VB.NET ]
Imports System
Imports System.Data.SqlClient
' We need this namespace to access web.config file
Imports System.Configuration
Partial Class DefaultVB
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Receive connection string from web.config
Dim myConnStr As String = ConfigurationManager.ConnectionStrings _
("YourConnectionStringName").ConnectionString
' Create new connection to database and open database
Dim myConn As SqlConnection = New SqlConnection()
myConn.ConnectionString = myConnStr ' Set connection string
myConn.Open()
End Sub
End Class
You can improve security of your web application if connection string in web.config file is not stored as plain text, but encrypted. If connection string is encrypted, malicious user will not get your connection string even if he or she read web.config. To learn more about how to encrypt connection string in web.config file check Encrypting Connection Strings in web.config file tutorial.
If you need to update existing or add new connection string at run time, see How To Modify Web.Config At Run Time tutorial.
Related articles:
1. Encrypting Connection Strings in web.config file
2. How To Modify Web.Config At Run Time