How to read value from Configuration file – ( app.config or web.config )

One of the best practice used in .NET application is to store the constants like Database connection in app.config in case of dll or standalone application or web.config in case of websites.

To achieve this, we have to follow below steps:

add reference of System.Configuration in .NET
add reference of System.Configuration in .NET

Lets consider below code in web.config

<appSettings>
    <add key="ConnectionString" value="Data Source=SHIVASOFTSHIVASOFT;Initial Catalog=testDb;
Integrated Security=True"/>
  </appSettings>

So, to read the key ConnectionString, we have to use below code in C#.

String dbConnection = System.Configuration.ConfigurationManager.
AppSettings["ConnectionString"];

Where “ConnectionString” is the key present in web.config or app.config.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.