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


This content was proof-read by Grammarly. You can Try Grammary for FREE

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.


Are you a .NET Developer planning to integrate GraphQL for .NET in your Application? Check out this book BUY & DOWNLOAD GRAPHQL.NET COOKBOOK

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;
%d bloggers like this: