How Do I Store and Access My Connection Strings in ASP.NET 2?

With ASP.NET 1.0 and 1.1 many people stored their connection strings in the Web.config file under the appSettings element. But is there a better way to save these settings in ASP.NET 2.0?

Yes, there is. ASP.NET 2.0 has a new ConnectionStringSettingsCollection called ConnectionStrings that provides easy access to your connection strings that you store in your Web.config file. All you need to do is add a <connectionStrings> element to your configuration file. To this element you can add your connection strings by adding <add> elements. You use the name attribute of the <add> element to specify the name by which you can retrieve the connection string in your code. You use the connectionString attribute to specify the connection string. Note that both attributes are case-sensitive. You should end up with the following <connectionStrings> element in your configuration file:

<configuration>
  <connectionStrings>
    <add name="YourConnectionName"
       connectionString="Integrated Security=SSPI;
          Persist Security Info=False;Initial Catalog=YourDatabase;
          Data Source=YourSQLServer"
       providerName="System.Data.SqlClient" />
  </connectionStrings>

Once you have added the connection string to your configuration file, you can retrieve it with the following code:

string MyConnectionString =
ConfigurationManager.ConnectionStrings["YourConnectionName"].ConnectionString;


At this point, MyConnectionString holds the connection string you defined in your configuration file.

The good thing about a separate <connectionStrings> element is that other config sections, like special Providers, can refer to those settings by the name of the connection string, instead of duplicating the connection string. You can retrieve more information about the connection besides the connection string. If you provide a providerName (as in the sample Web.config above) you can retrieve the providers's name in code as well. This can be useful if you're working with the new factory model in your data access layer and need to know with which data provider you're currently working.


Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article .


Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.



Feedback by Other Visitors of Imar.Spaanjaars.Com

On Wednesday, December 29, 2004 3:42:30 PM Jos Branders said:
The information was very useful.

There's a small mistake on this page: it's not "addname", but "add name" with a space.
On Wednesday, December 29, 2004 4:22:03 PM Imar Spaanjaars said:
Fixed! Thank you.
On Friday, March 17, 2006 5:50:45 AM K.Arun Kishore said:
The article like creating Message Box, storing Connection string are very helpful to me in doing my Online Project. Keep Going.

Will you help me, How to Generate Log files in ASP.NET2.0?
Please give me an Overview if Possible.

Thanks

K.Arun Kishore
On Saturday, March 18, 2006 8:35:58 AM Imar Spaanjaars said:
Hi Arun,

Can you tell me what log files you are referring to??

Imar
On Saturday, March 18, 2006 9:37:09 AM K.Arun Kishore said:
Thanks for your Response. The Log file means...

I have to set the logfile options at Admin console (drop down menu)  to None, Medium and Complete and their corresponding global values are 0, 1 and 2.
If the global value is 0 (None)then do not track any logs.
If the global value is 1 (Medium)then i must do the following:
Beginning of the each routine, log the name of the procedure and all passing parameters on to the log file
End of the routine log the name of the procedure and processed value.
If the global value is 2 (Complete)then
            In addition to Medium level of Log as stated above , do the following
Every major operation of the routine (example before getting any value log the entry and value and after getting the value log the value – detailed log )

Thanks

K.Arun Kishore
On Sunday, March 19, 2006 8:39:06 PM Imar Spaanjaars said:
Hi Arun,

This is not an easy requirement to fulfill, and it's definitely too complex to explain / discuss this as a response to an article at my site.

Instead, I suggest you post your question at the Wrox forum over at http://p2p.wrox.com. If you do so, please be sure to provide as much information and background as possible, so people on the forum can make good suggestions about implementing such a logging mechanism....

Cheers,

Imar
On Monday, March 20, 2006 5:50:38 AM K.Arun Kishore said:
Thanks Imar for your Kind Response.
On Friday, April 21, 2006 1:53:55 PM ArunKishore.K said:
Hi Imar,

How to handle ArrayList.Item in C#?

Is there any tool for converting ASP.NET/VB to ASP.NET/C#?

Thanks

ArunKIshore.K
On Saturday, April 22, 2006 9:44:01 AM Imar Spaanjaars said:
Hi ArunKishore,

How is this related to storing connectionstrings in .NET 2.0??

Imar
On Wednesday, August 02, 2006 10:25:57 PM Thad Fiebich said:
Hey thanks! Was beating my head for a few days trying to make something work that I was actually doing the wrong way!

Your above example was very helpful and it worked!

nice job!
On Monday, April 02, 2007 9:00:54 AM sai said:
it's a nice article
On Wednesday, April 04, 2007 4:17:16 PM Steve Holden said:
Much more useful than many other articles, which seem to refer to ASP.NET 1. Thanks - just the information I needed!
On Wednesday, April 11, 2007 4:06:57 PM Raymond Boone said:
Hi Imar,

I've defined a connection string in my web.config file as follows:

[connectionStrings]
    [add name="OTCMS"
       connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\dessrv8\otcms\otcmst.mdb"/]
[/connectionStrings]

I'm attempting to access it as follows:
[asp:AccessDataSource id="NameofClient" runat="server"
DataFile="[%$ connectionStrings:OTCMS %]"
SelectCommand="SELECT DISTINCT [CaseNumber], [ClientID], [Status], [LastName] + ', ' + [FirstName] AS FullName FROM [Main]"
FilterExpression="[Status] LIKE '{0}'"
]

I get the following error when I try to access the website:
'c:\dessrv8\otcms\otcmst.mdb' is not a valid path.  Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.

Can you help me sort it out? I can't figure out why it's putting c:\ in place of part of the UNC path.
On Wednesday, April 11, 2007 4:46:45 PM Imar Spaanjaars said:
Hi Raymond,

You may need to double the slashes in the connection string.

If that doesn't help, check the permissions for the UNC path for the webserver's account. If that doesn't help, do a Google search for the exact error message. This issue has been reported many times...

Imar
On Wednesday, April 11, 2007 6:39:28 PM Raymond Boone said:
Imar,

I've tried doubling the slashes, checked permissions, and Googled, but still come up clean. I have found others with the problem, but none of the suggested fixes have gotten me there.

I can make it work if I put the connection string in the DataFile path on each page--but when the DB changes (and I do this regularly as a I have a production DB and a testing DB), I have to update individual pages.

Thanks for the suggestions--and I've been a fan of your site since I started this project (it's helped a lot).
On Wednesday, April 11, 2007 6:46:34 PM Imar Spaanjaars said:
Hi Raymond,

Glad you like my site; sorry I can't help you much further with this.

Imar
On Wednesday, April 11, 2007 7:29:52 PM Raymond Boone said:
Ok...finally figured this out and thought I'd share just in case someone else has a similar problem.

Here's my original connection string from web.config:
[connectionStrings]
    [add name="OTCMS"
       connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\dessrv8\otcms\otcmst.mdb"/]
[/connectionStrings]

And here's what it needed to be:
[connectionStrings]
    [add name="OTCMS"
       connectionString="\\dessrv8\otcms\otcmst.mdb"/]
[/connectionStrings]

Turns out that for an AccessDataSource, you don't have to specifiy the Provider--you only have to do that for an SQLDataSource. Found the infor here after I acutally read the page: http://msconline.maconstate.edu/tutorials/ASPNET20/ASPNET03/aspnet03-02.aspx

Thanks again for doing this site.
On Wednesday, April 11, 2007 7:39:20 PM Imar Spaanjaars said:
Hi Raymond,

Thanks for the update....

Imar
On Friday, May 25, 2007 1:04:55 AM MJ said:
Much more useful than many other articles! Thanks!
On Thursday, June 07, 2007 4:58:45 PM subrata kundu said:
I want to connect MySql with asp.net2.0.How I will do that?
On Thursday, June 07, 2007 7:22:07 PM Imar Spaanjaars said:
Hi subrata,

I think a Google search should give you many useful results.

Imar
On Thursday, August 09, 2007 1:32:27 AM Steve said:
Hello,

I was wondering if you have any information on the ASP.Net Configuration Tool?  I had it working, but now it only give 'error occurred... please go back a page"   My connection works fine when I run the site in my browser, but I am getting 2 ASP.Net Development Server icons running in my tray, one for my site:

D:\Documents and Settings\Stephen J. Dooley\My Documents\MSDN\Learn Visual Web Developer 2005 Express Edition-C#-Lesson 14\Snapshot6\QuizCS\

and for the tool:

http://localhost:3605/asp.netwebadminfiles/error.aspx#-Lesson%2014\Snapshot6\QuizCS\&applicationUrl=/QuizCS

Answers have been pretty hard to find, although it seems to be a frequent topic on blogs.  Also, I'd like to set IIS (5.1) correctly as well.  Any help would be appreciated.  Thanks

On Thursday, August 09, 2007 6:01:49 AM Imar Spaanjaars said:
Hi Steve,

Sorry, I have no idea what could be the cause of or the solution to this problem.

By default, you can't use the configuration tool with IIS on a domain; you can only access it from within Visual Web Developer.
For more information about setting up IIS, consult the ASP.NET / IIS documentation, or try posting this in a forum like http://p2p.wrox.com/

Cheers,

Imar
On Thursday, August 09, 2007 4:56:28 PM Steve said:
Imar,

Thanks for the response.  This really has nothing to do with IIS (although a counterpart has always been available within IIS).  This new feature in VS 2005 is just a VB website that is installed locally with VS install.  I have even browsed to it as a 'new website', similar to how you would access any sample on the file system.  When I try to compile or run it, it shows at least 20 errors in the error log, and the result is that it produces the same error screen I see when I use it as designed from VS on any other web site I'm working on.  Is there any way to just repair this?  Anyway thanks for the comments, and I'll try some other blogs. (This has always been my biggest complaint- a sample just doesn't work, and I spend all my time trying to make it so instead of learning about the feature it demonstrates)
On Thursday, August 09, 2007 5:28:54 PM Imar Spaanjaars said:
Hi Steve,

You said:

>> I'd like to set IIS (5.1) correctly as well.

so I thought you were referring to IIS. ;-)

Regarding the Admin Tool files: why did you try to build them? Usually, in a standard site, all you need to do is this:

1. Choose File | New Web Site in VS 2005 to create a new site.
2. Open the WSAT (Website Administration Tool) from the Website menu.

The WSAT should open and should allow you to configure your site.

If that doesn't work, your VS 2005 setup is corrupt and you may need to reapir it by running setup again.

Finally, what sample are you referring to when you say:

>> This has always been my biggest complaint- a sample just doesn't work, and I spend all my time trying to make it so instead of learning about the feature it demonstrates

Cheers,

Imar
On Thursday, August 09, 2007 7:26:26 PM Steve said:
Imar,

I'm working with a lot of samples, some from CodeProject, some from ASP.Net Site;  It just seems to me that up to 50% just do not install or run correctly, and require a lot of manipulation just to get them to run.  My goal is to learn or utilize a cool feature, not to figure out the miriad problems setting something up.  Anyway, I tried to load the ASP.Net Configuration tool just to see if I could determine the problem that was causing it to fail.  It's just another web site on my file system that's installed with VS2005.  I'm gonna use my install disks to see if it will repair;  barring that, I'll just have to code the Web.Config by hand (like I used to do).   I do not think that the ASP.Net Development Server should open up twice (one for the tool, one for the site I'm designing) on 2 separate ports- this probably is a symptom of the corruption.  Finally, I've seen a lot of article on how to use it, but almost nothing on how to fix problems- and a lot of posts on problems- so I'm not the only one.  BTW, the web site I'm working on opens up fine.  The config tool is the problem.  Great site you have- I'm sure I'll be back for more cool ideas.  Thanks
On Friday, August 10, 2007 9:19:38 PM Imar Spaanjaars said:
Hi Steve,

I see; hopefully you don't have the same experience with the articles on my web site. My goal is to make them "hit and run" type of projects / articles.

Regarding the two web servers: that should normally not be the case. I have seen it before, but usually it should work as I described in my earlier reply.

Imar
On Friday, August 10, 2007 11:33:50 PM Steve said:
Hi Imar,

I was looking at a video demonstrating the Web Config Tool, and it also had 2 instances of the ASP.Net Development Server, and the presenter is an MS MVP- so it must be correct.   I also wanted to let you know that re-running the VS 2005 install under 'Repair' fixed the problem.  I'm not sure how it all got corrupted, but it takes several hours to do that process, so I'd really not like to repeat it.  I think a lot of the problems I have with samples is that many of the settings are hard coded, and there isn't adequate documentation of where these changes need to be made for your PC.  Another thing that confused me is that in the past, VS 2003 and earlier were always part of a project/solution, and now this seems to be optional in VS 2005 with Web Site/Web Projects.  Also, the video was using 2005 Web Express, so it may be different as well.  Cheers
On Saturday, August 11, 2007 9:57:11 AM Imar Spaanjaars said:
Hi Steve,

I see what you mean now. This is expected behavior; one web server opens at the address for the WSAT. E.g.:

http://localhost:52945/asp.netwebadminfiles/

while the other opens your site's root. E.g.:

http://localhost:63543/WebSiteName/

or

http://localhost:63543/

The numbers are random, so they are different in your situation, but the idea is still the same.

Glad you were able to fix it by reinstalling VS 2005. Usually, you don't want to touch / change the files in the asp.netwebadminfiles of the Framework folder under your Windows folder.

Cheers,

Imar
On Thursday, August 16, 2007 4:18:50 PM Norman said:
Hi Imar,


I really need to know how I could prompt the users  to enter   the UserName and the PassWord and then store that information in  global ConnectionString in the Web.Config or Global.Asax files. Is that possible.Please, Help me out!. I new in ASP.NET
On Thursday, August 16, 2007 6:05:38 PM Imar Spaanjaars said:
Hi

Search Google for "write to web.config" and you'll find some interesting stuff that describes how to do this.

Cheers,

Imar
On Tuesday, February 19, 2008 2:36:47 PM pradeep said:
Hi,

Its good article.
On Friday, April 30, 2010 6:05:42 AM yamuna matherw said:
good.....thanks

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.

For more information about the Talk Back feature, check out this news item.