Click here to Skip to main content
15,880,608 members
Articles / Web Development / ASP.NET

How to Store and Retrieve a ConnectionString from a Web.Config or App.Settings File

Rate me:
Please Sign up or sign in to vote.
3.30/5 (17 votes)
26 Mar 2009CPOL4 min read 119.5K   27   17
How to Store and Retrieve a ConnectionString from a Web.Config or App.Settings File

Introduction

Every time in my career when I learn something new, I always wish to share it. Every time when someone is new to a subject, at least he has to Google before he can post in the Forum. Sometimes the answers that are found in threads are not complete. I would like to take this chance to increase the pages and results found when you Google the subject “How to Store a Connection string in an App.Config file or Web.Config File. Let’s hear my story first.

Background

Every time I write an article, it means I grew to a certain level of understanding. When I came to the .NET world, I was so overwhelmed to create applications. My interest was on Windows applications, I was not that interested in developing Web applications, may be it’s because of the projects I was involved with. Sometimes I would just consume web services from a Windows application. I had fun and I loved ADO.NET as you have seen in my previous articles. I enjoyed database programming and I have learned a lot and am still learning to make my data layers the most beautiful thing in my world. Let’s cut to the chase. Recently I have been hard coding my connection string to a DLL (Data Access Layer). There was nothing wrong with that, because I knew for a fact that My Server name would never change for years. But that is where I made a big mistake, especially on a Windows application. After a while, I mean few weeks ago, the server that had held my database had resigned. Well the database had to be moved to another server, but hey this meant I have to recompile my DLLs. It is because I cannot change my connection string without recompiling my DLLs. It was never going to be a good thing to change the connection and recompile the DLL again. That means I had to look for a way to store the connection string. I have learned that I should never hardcode my connection string or anything that has to do with my application settings. In this article, we are going to look at how to place a connection string in a file that can be opened and edited anytime when the server changes or the password changes.

Using the Code

We are going to use multiple comments in our article and we are going to use C# as our language.

Start

This is a very short story that is going to have a happy ending. To store a connection string to an App.Config file, you must do the following; Open your Visual Studio on an Existing Project to which you have once hard coded your connection string. Add a new Application.Configuration file:

Image 1

In your project, the file will be named App.config by default. Open the file. Now we are going to add our connection string, like this:

XML
<add key="MyConstring" Value = "User Id=sa; 
    Password=password;Server=Myserver;Database=Mydatabase "></add>

That means our file will look like this:

XML
<?xml version="1.0" encoding="utf-8" ?>
< configuration>
< add key="MyConstring" Value = "User Id=sa; 
    Password=password;Server=Myserver;Database=Mydatabase "></add>
< /configuration>

Now remember that your connection string should be added between your configuration tags. Now that you have added your connection string, you have to access it from your C# or VB.NET code, but in this article I will be doing demonstrations in C#, but these languages do not differ that much. Now the first thing we need to do is to add a Reference to a System.Configuration namespace. After that, we are going to our usings and add it like this:

C#
using System.Configuration;

After you are done, let's go to a string that you once hardcoded. It will be something like this:

C#
String strcon = "User Id=sde; Password=topology;
    Server=bkiicoryw004;Database=Tshwane_Valuations "

Now convert it to this:

C#
string strcon = ConfigurationManager.AppSettings.Get("MyConstring");

Then recompile your project. When you deploy your application, your App.Config will be deployed amongst other dependency, because your application will need the file to be told where the data source is sitting. So the next time the Server name changes or the password changes, you don't have to recompile your application, you just go to your Program Files and locate your Application directory and open the App.config with a text file and change the connection string. The above example is for Windows applications, but for Web applications, you have to add a Web.Config file as I did and add your connection string like this:

XML
<configuration>
    <appSettings>

< add key =" MyConstring " value ="User id=sa;
    Password=password;Server=myserver;Database=mydb"></add>
        </appSettings>

</configuration>

When you access it from your code, it should look like this:

C#
string strcon = ConfigurationSettings.AppSettings["MyConstring"];

This is the END of the story.

Conclusion

At least the story has a happy ending. The next time a server changes, you don't need to recompile. When the password changes, you don't need to recompile.
Hope you loved my short story.
Thank you.
Ngiyabonga

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Vimalsoft
South Africa South Africa
Vuyiswa Junius Maseko is a Founder of Vimalsoft (Pty) Ltd (http://www.vimalsoft.com/) and a forum moderator at www.DotnetFunda. Vuyiswa has been developing for 16 years now. his major strength are C# 1.1,2.0,3.0,3.5,4.0,4.5 and vb.net and sql and his interest were in asp.net, c#, Silverlight,wpf,wcf, wwf and now his interests are in Kinect for Windows,Unity 3D. He has been using .net since the beta version of it. Vuyiswa believes that Kinect and Hololen is the next generation of computing.Thanks to people like Chris Maunder (codeproject), Colin Angus Mackay (codeproject), Dave Kreskowiak (Codeproject), Sheo Narayan (.Netfunda),Rajesh Kumar(Microsoft) They have made vuyiswa what he is today.
This is a Organisation

4 members

Comments and Discussions

 
QuestionServing connection in App.config Pin
Member 886365524-Apr-12 13:47
Member 886365524-Apr-12 13:47 
GeneralMy vote of 5 Pin
ashishkumarjha28-Sep-10 17:49
ashishkumarjha28-Sep-10 17:49 
GeneralOK - SO now instead of recompiling - BUT ... Pin
pjctx10-Mar-10 5:11
pjctx10-Mar-10 5:11 
GeneralRe: OK - SO now instead of recompiling - BUT ... Pin
Vimalsoft(Pty) Ltd11-Mar-10 2:14
professionalVimalsoft(Pty) Ltd11-Mar-10 2:14 
GeneralMy vote of 1 Pin
Padte24-Nov-09 18:05
Padte24-Nov-09 18:05 
GeneralRe: My vote of 1 Pin
Alaric Dailey4-Feb-10 17:26
Alaric Dailey4-Feb-10 17:26 
Generalusing global.asax.... Pin
greendragons9-Sep-09 0:37
greendragons9-Sep-09 0:37 
GeneralRe: using global.asax.... Pin
Vimalsoft(Pty) Ltd9-Sep-09 0:43
professionalVimalsoft(Pty) Ltd9-Sep-09 0:43 
GeneralRe: using global.asax.... Pin
greendragons9-Sep-09 0:50
greendragons9-Sep-09 0:50 
GeneralRe: using global.asax.... Pin
Vimalsoft(Pty) Ltd9-Sep-09 0:51
professionalVimalsoft(Pty) Ltd9-Sep-09 0:51 
GeneralStill too inflexible Pin
PIEBALDconsult20-Aug-08 7:29
mvePIEBALDconsult20-Aug-08 7:29 
GeneralRe: Still too inflexible Pin
Vimalsoft(Pty) Ltd20-Aug-08 8:57
professionalVimalsoft(Pty) Ltd20-Aug-08 8:57 
GeneralThis is fine for the days before .NET 2.0 Pin
jklucker20-Aug-08 7:13
jklucker20-Aug-08 7:13 
GeneralRe: This is fine for the days before .NET 2.0 Pin
Vimalsoft(Pty) Ltd20-Aug-08 9:01
professionalVimalsoft(Pty) Ltd20-Aug-08 9:01 
GeneralRe: This is fine for the days before .NET 2.0 Pin
GaryGreen28-Mar-09 6:16
GaryGreen28-Mar-09 6:16 
GeneralRe: This is fine for the days before .NET 2.0 Pin
Alaric Dailey4-Feb-10 17:29
Alaric Dailey4-Feb-10 17:29 
GeneralRe: This is fine for the days before .NET 2.0 Pin
Vimalsoft(Pty) Ltd7-Feb-10 19:17
professionalVimalsoft(Pty) Ltd7-Feb-10 19:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.