How to get a Connection String from Web.Config or App.Config in C#

Connection Strings can be placed in the Web.Config or App.Config in .NET so that the connection strings are not hard-coded into the programs. This flexibility allows the site or application to be installed on servers or on client sites with the maximum of ease.

Connections String are formatted the same and placed in the same locations in both the web.config and app.config files. There's no need to write separate code for getting the connection string in web as opposed to an application. Open the .config file in your .NET application and you should see something like this at the top.

<?xml version="1.0" encoding="utf-8"?>
<!--
    For more information on how to configure your ASP.NET application, please visit
    https://go.microsoft.com/fwlink/?LinkId=301880
    -->
<configuration>

The connection strings go immediately after the <configuration>, it is case sensitive so if it doesn't work first time, check the connection string. Below is an example of a connection string, you will need to update it for your own configuration.

    <connectionStrings>
        <add name="ProjectDB"
            connectionString="Data Source=127.0.0.1;Initial Catalog=ProjectDB;Integrated Security=True"
            providerName="System.Data.SqlClient"/>
    </connectionStrings>

If you're still unsure where it goes, Visual Studio will help you out with its autocomplete function. When you press the < key, if connectionStrings doesn't appear in the list then you've put it in the wrong place and need to look elsewhere.

In your Web or Desktop application, you need to make sure you have a reference to System.Configuration in order to use the functions that retrieve the values from .config file. At the top of the code, add :-

using System.Configuration;

To use access the connection string in code, use the following line. Remember the name of the connection string

string sConn = ConfigurationManager.ConnectionStrings["ProjectDB"].ConnectionString;

The format of the connection string will depend on the database or system that you wish to connect to. Connection Strings website is a very good resource if you can't work out the format of the connection string that you require.

Tags - .NET

Last Modified : June 2023


About... / Contact.. / Cookie...