Storing Database Connection Strings in App.Config

Waqas Anwar
08 April 2008

Storing database connection strings in source code can lead you to some security issues and can also cause you maintenance problems. It is always recommended that you keep your connection strings in a separate configuration file so that you can change database connection related information such as password or database name without even modifying or recompiling your source code.

.NET Framework 2.0 added a separate configuration section in both Windows Application configuration (App.config) and Web Application configuration (Web.config) file. Developers can use these section to store connection string information such as a connection string name or provider type etc. In the following tutorial I will show you how you can store and retrieve connection string information in .NET Windows Application using C#.
The following code shows how you can store connection strings in App.config file.

<?xml version="1.0" encoding="utf-8" ?>
      <add name="MyDBConnectionString" providerName="System.Data.SqlClient"
            connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />

Once you have saved your connection string in App.config file you can use System.Configuration.ConfigurationManager class to read this connection string in code.

ConnectionStringSettings  conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];
ConnectionStringsSettings class provides properties to read connection string settings in your program as following code shows.

string name = conSettings.Name;
string providerName = conSettings.ProviderName;
string connectionString = conSettings.ConnectionString;