Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
15 Oct 2013 5  
This code helps you to grab ConnectionString from App.config.

Introduction

We always use Connection String in forms that we design but when you design a big software you should set the connection string for once and use it in many forms. In this method you use the name of the Connection String instead of the connection string text. 

Every time you want to change the connection string just change the main connection string in the App.Config file.

By this method you don't need to change all of the forms in your project, just change the Connection String in the App.Config.

Using the Code

First of all you should set the connection string in the App.Config file. For example I set the connection string for my database as you see here:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="CharityManagement" 
    connectionString="Data Source=.;Initial Catalog=CharityManagement;Integrated Security=True"/>
  </connectionStrings>
</configuration> 

After that you use the connection string in your forms using this code:

In your forms you set references that you want to use:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

Then you can get the Connection String from the App.Config by using the ConnectionStrings property.

var connectionString=ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;

You can use this method in both Windows Forms and ASP.NET projects.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here