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

By , 26 Mar 2009
 

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)

About the Author

Vuyiswa Maseko
Software Developer (Senior) Dotnetfunda
South Africa South Africa
Member
Vuyiswa Junius Maseko is a programmer and a moderator in ".NetFunda. Vuyiswa has been developing for 8 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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionServing connection in App.configmemberMember 886365524 Apr '12 - 13:47 
Many thanks Vuyiswa, this was a missing link to another code project which described this non-hard coded connection method but did not explain the changes in the app.config file.
Smile | :) Smile | :)
GeneralMy vote of 5memberashishkumarjha28 Sep '10 - 17:49 
its really helpful
GeneralOK - SO now instead of recompiling - BUT ...memberpjctx10 Mar '10 - 5:11 
OK,
 
As always, thank you to everyone who writes these articles.
 
In my case, another application has already created a slew of web.config and *.config files all over the place.
 
I need to programatically change all these existing connecting strings.
 
I want to read them in, display the existing one is a text box or gridview, then write a new connectionString based on variables I collect in my app. Manually editing files is bad!
 
Any thoughts?
GeneralRe: OK - SO now instead of recompiling - BUT ...memberVuyiswa Maseko11 Mar '10 - 2:14 
Having a lot of Web config files is not a good idea. you might even get Errors that are encountered here
 
http://www.dotnetfunda.com/forums/thread1488-i-got-error-in-webconfig.aspx[^]
 
Only one web Config for a Web Application is enough unless you have a Good reason to add more. It is not a Good idea to edit the web config at Run-time. A better approach is to do a replace onfly. I have an application that connect to different Database and i i have following in my Connection string in the webconfig
< add name="oDirectConnectionString" connectionString="Data Source=www\wwww;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=sa;Password=oops" providerName="System.Data.SqlClient"/>
 

and in my DAL(Data Access Layer) i have a Function that Replaces the values of the Connectionstring without altering it like this
 

 private string GetConnectionString(string DB) // where DB is your database name from the session
        {
 
            string connString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
 
            if (DB != null)
            {
                return connString.Replace("MyDatabase", DB);
            }
            else
            {
                return connString.Replace("MyDatabase", "MyDatabase");
            }
 
        }
 
as you can see i replace the "MyDatabase" with the Database that i want to change to. Mybe in your case you have find out that all settings change, you can also do this its faster and convinient.
 
Kind Regards
Vuyiswa Maseko,
 
Spoted in Daniweb-- Sorry to rant. I hate websites. They are just wierd. They don't behave like normal code.
 
C#/VB.NET/ASP.NET/SQL7/2000/2005/2008
http://www.vuyiswamaseko.com
vuyiswa@its.co.za
http://www.itsabacus.co.za/itsabacus/

GeneralMy vote of 1memberPadte24 Nov '09 - 18:05 
I was expecting the connection strings section explained, not app settings
GeneralRe: My vote of 1memberAlaric Dailey4 Feb '10 - 17:26 
Try my article instead!
 
Don't hard code your DataProviders
Generalusing global.asax....membergreendragons9 Sep '09 - 0:37 
gud stuff lol .....Same we can do by using global.asax also.....declaring con string in session....what will b da disadvantage?
GeneralRe: using global.asax....memberVuyiswa 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....membergreendragons9 Sep '09 - 0:50 
Thnx lol...nw i have 2 replace my session string with webconfig lol....
GeneralRe: using global.asax....memberVuyiswa Maseko9 Sep '09 - 0:51 
yes
 
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/

GeneralStill too inflexiblememberPIEBALDconsult20 Aug '08 - 7:29 
I never store a connection string at all. And I also don't use App.Settings; I use an XML file to store the information required for my library to cobble up the connection string on the fly. The XML file can then be used by many different applications which need to access the various databases I use.
GeneralRe: Still too inflexiblememberVuyiswa Maseko20 Aug '08 - 8:57 
Wow nice,You store a Connection String in one XML File and you access it from Different Applications. How do you do that?
 
Thanks for sharing Idea
 
Vuyiswa Maseko,
 
Sorrow is Better than Laughter, it may Sadden your Face, but It sharpens your Understanding
 
VB.NET/SQL7/2000/2005
http://vuyiswamb.007ihost.com
http://Ecadre.007ihost.com
vuyiswam@tshwane.gov.za
 

GeneralThis is fine for the days before .NET 2.0memberjklucker20 Aug '08 - 7:13 
When .NET 2.0 first appeared it fixed the storing of connection strings in the application/web config file by adding a new section called connectionsstrings. The schema allows you to name your connection, provide the actual connection string and also allows you to specify the provider.
<connectionStrings>
    <add name="ConnectionName" connectionString="Data Source=<Database>;Initial Catalog=<Catalog Name>;Integrated Security=True;
user id=<Username>;password=<Password> providerName="System.Data.SqlClient"/>
      </connectionStrings>
 
All you need then to do is reference the System.Configuration DLL and use the following
 
ConfigurationManager.ConnectionStrings("ConnectionName").ConnectionString
 
You are all done!
 
I reject your reality and substitute my own!
- Adam Savage, Mythbuster
-George W Bush
 
life is like a roll of toilet paper. The closer it gets to the end, the faster it goes.
 
My definition of an expert in any field is a person who knows enough about what's really going on to be scared.
- PJ Plauger

GeneralRe: This is fine for the days before .NET 2.0memberVuyiswa Maseko20 Aug '08 - 9:01 
Nice , Thanks for your input. it means a lot
 
Thanks
 
Vuyiswa Maseko,
 
Sorrow is Better than Laughter, it may Sadden your Face, but It sharpens your Understanding
 
VB.NET/SQL7/2000/2005
http://vuyiswamb.007ihost.com
http://Ecadre.007ihost.com
vuyiswam@tshwane.gov.za
 

GeneralRe: This is fine for the days before .NET 2.0memberghagreen@comcast.net28 Mar '09 - 6:16 
Using the connectionstrings section doesn't really add anything unless you are trying to specify the database at runtime using the provider settings. Usually I just put my connection strings in the appSettings section like the article says.
GeneralRe: This is fine for the days before .NET 2.0memberAlaric Dailey4 Feb '10 - 17:29 
If you don't use the providerName, you have to hardcode your provider, if you hardcode your provider, you limit which DBs your clients can use.
 
Things like that, like Sunbelt Softwares products, irk me when the functionality is built into .NET if coders aren't lazy.
GeneralRe: This is fine for the days before .NET 2.0memberVuyiswa Maseko7 Feb '10 - 19:17 
true
Vuyiswa Maseko,
 
Spoted in Daniweb-- Sorry to rant. I hate websites. They are just wierd. They don't behave like normal code.
 
C#/VB.NET/ASP.NET/SQL7/2000/2005/2008
http://www.vuyiswamaseko.com
vuyiswa@its.co.za
http://www.itsabacus.co.za/itsabacus/

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

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