How to read a connection string from web.config file in ASP.NET ?

Assume that you have a connectionstring configured in the web.config file of your ASP.NET application and you wish to read it using C# within your application.

How to read a connection string from web.config file in ASP.NET ?

You can easily do that using the ConfigurationManager class defined in the System.Configuration namespace.

1. Ensure that the System.Configuration assembly is referenced in your project.

2. Add the using directive in your code to import the namespace.

3. Retreive the connection string from the web.config using the System.Configuration.ConfigurationManager.
    ConnectionStrings option as shown

var connectionStr = System.Configuration.ConfigurationManager.
    ConnectionStrings["connection1"].ConnectionString;
Tags :

Leave Your Comment

Liked this content?. Please spread the word :)