Store Connection String in Web.config

It is very easy to store the connection string in a config file and there are several benefits in doing so. This article describes why and how to store the connection string in web.config.
Written by: Sebastian Affakes

It is a good practice to store the connection string for your application in a config file rather than a hard coded string in your code. The way to do this differs between .NET and older before NET 2.0 applications. This article cover both. The examples is applicable also to .NET applications using app.config.

Connection string in .NET config file

Do not use the appSettings section in web.config. Instead use the connectionStrings section in web.config.

<?xml version="1.0" encoding="utf-8"?>
    <add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />

To read the connection string into your code, use the ConfigurationManager class.

string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

Remember to add a reference to the System.Configuration component. Then include the namespace System.Configuration to get access to the ConfigurationManager class.

// C#
using System.Configuration;

// VB.Net
imports System.Configuration

Clear connection strings coming from higher level config files

Configuration files are hierarchical, with machine.config being at the highest level. You can clear connection strings defined earlier in the hierarchy to make sure any unwanted settings don't bubble down to your desired value.

<?xml version="1.0" encoding="utf-8"?>
   <clear /> <!-- clear all other connection strings -->
   <add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />

Adding <clear /> at top in the connectionStrings section is usually a good practice to make sure no other connection strings are bubbling down from a higher level configuration file.

Connection string before .NET 2.0 config file

Use this information only for old .NET 1.0 and .NET 1.1 applications. In the appSettings location, add a key named whatever you like to reference your connection string to.

  <add key="myConnectionString" value="server=localhost;database=myDb;uid=myUser;password=myPass;" />

To read the connection string from code, use the ConfigurationSettings class.

string connStr = ConfigurationSettings.AppSettings("myConnectionString");

Now you have the connection string loaded from web.config into your string variable in code.


Always store the connection string in a config file. It's not any harder once you get used to it and you will benefit from it as it is much easier to change connection string properties when your application is in production.

Connect to