ASP.NET: How to get a specific ConnectionString from the Web.Config by name
Dec 28, 2005 • Chris Pietschmann • ASP.NETYou 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.

Chris Pietschmann
DevOps & AI Architect | Microsoft MVP | HashiCorp Ambassador | MCT | Developer | Author
I am a DevOps & AI Architect, developer, trainer and author. I have nearly 25 years of experience in the Software Development industry that includes working as a Consultant and Trainer in a wide array of different industries.