Click here to Skip to main content
Click here to Skip to main content

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

, 26 Mar 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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:

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

That means our file will look like this:

<?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:

using System.Configuration;

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

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

Now convert it to this:

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:

<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:

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)

Share

About the Author

Vuyiswa Maseko
Software Developer (Senior) Dotnetfunda
South Africa South Africa
Vuyiswa Junius Maseko is a programmer and a moderator in ".NetFunda. Vuyiswa has been developing for 15 years now. his major strength are C# 1.1,2.0,3.0,3.5 and sql and his interest are in Silverlight,WPF,C#. He has been doing a lot of Silverlight development. He has been using .net since the beta version of it. He is also an online Trainer at www.Itfunda.com. Thanks to people like Sheo Narayan (.Netfunda) , Chris Maunder (codeproject), Colin Angus Mackay (codeproject), Dave Kreskowiak (Codeproject),.They have made vuyiswa what he is today.
Follow on   Twitter

Comments and Discussions

 
QuestionServing connection in App.config PinmemberMember 886365524-Apr-12 13:47 
GeneralMy vote of 5 Pinmemberashishkumarjha28-Sep-10 17:49 
GeneralOK - SO now instead of recompiling - BUT ... Pinmemberpjctx10-Mar-10 5:11 
GeneralRe: OK - SO now instead of recompiling - BUT ... PinmemberVuyiswa Maseko11-Mar-10 2:14 
GeneralMy vote of 1 PinmemberPadte24-Nov-09 18:05 
GeneralRe: My vote of 1 PinmemberAlaric Dailey4-Feb-10 17:26 
Generalusing global.asax.... Pinmembergreendragons9-Sep-09 0:37 
GeneralRe: using global.asax.... PinmemberVuyiswa Maseko9-Sep-09 0:43 
Declaring a ConnectionString on Global.asax is not a good idea. Global.aspx is Good for other purposes not the Connectionstring. Well in Classic ASP , we used it , because we did not have an option like the web config. if you go the web config way, you will not need to go the Session way
 
Vuyiswa Maseko,
 
Few companies that installed computers to reduce the employment of clerks have realized their expectations.... They now need more and more expensive clerks even though they call them "Developers" or "Programmers."
 
C#/VB.NET/ASP.NET/SQL7/2000/2005/2008
http://www.vuyiswamaseko.com
vuyiswa@its.co.za
http://www.itsabacus.co.za/itsabacus/

GeneralRe: using global.asax.... Pinmembergreendragons9-Sep-09 0:50 
GeneralRe: using global.asax.... PinmemberVuyiswa Maseko9-Sep-09 0:51 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.141022.2 | Last Updated 26 Mar 2009
Article Copyright 2008 by Vuyiswa Maseko
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid