Chris Pietschmann

husband, father, hacker, entrepreneur, futurist, innovator, autodidact

NAVIGATION - SEARCH

ASP.NET: How to get a specific ConnectionString from the Web.Config by name

You have your ConnectionString for your ASP.NET web app stored in the Web.Config file. Now how exactly how do you get that ConnectionString out of there from within your code?

Sample Web.Config section with a ConnectionString:

<connectionStrings>
    <remove name="LocalSqlServer" />
    <add name="LocalSqlServer"
        connectionString="Data Source=myDBServer;database=myDB;Integrated Security=True;"
        providerName="System.Data.SqlClient"/>
</connectionStrings>

Now lets get the ConnectionString from the Web.Config file with only one line of code (C#):

var conString = ConfigurationManager.ConnectionStrings["LocalSqlServer"];
string strConnString = conString.ConnectionString;

and with Visual Basic .NET:

Dim conString = ConfigurationManager.ConnectionStrings("LocalSqlServer")
Dim strConnString As String = conString.ConnectionString

Now isn't that simple? I'm posting this because I did a search and didn't find an example of how to do this. I had to poke around a little and discover this on my own. I hope this helps someone avoid some frustration.

blog comments powered by Disqus