7 February 2014

How to configure and read connection string in web.config file?



Storing connectionString in web.config file is a good practice instead of hard code in c# file. Here I’m using .net 3.5 for this sample.

<connectionStrings>
    <add name="ConnectionString"
         connectionString="Data Source=TEST-PC\SQLEXPRESS;Initial Catalog= TEST_DB;Integrated Security=True"
         providerName="System.Data.SqlClient"/>
 </connectionStrings>

Here we need to use connectionString section instead of appsettings as like in .net 2.0 also see the below how to read this connection string in code file while opening the connection. For this we need to add/include the reference System.Configurence namespace.

string Con = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

No comments:

Post a Comment