Now here in this tutorial, I’ll explain how to read or get connectionstring from web.config file using c# as well as vb.net in Asp.net. Read the full tutorial to get a clear cut idea on how to obtain connectionstring from web.config file. If you feel that that the tutorial was worth your time, then please do check out our previous tutorials as well as I mentioned below.
In my previous tutorials, I’d explained about appSettings vs connectionStrings in web.config file, sql injection with example and other more amazing tutorials on connectionStrings, Asp.net here.
Get ConnectionString from Web.config File
Before starting how to read or get connectionstring from web.config file, you should know how to get connection string to connect your database from here that will show you also the difference why I’ve not used user id and password in my connection string. After knowing that, you can adjust your connection string in web.config as follows.
<add name=“myDbConnection” providerName=“System.Data.SqlClient”
connectionString=“Data Source=myServer;Integrated Security=true;Initial Catalog=myDatabase“/>
To read or get connectionstring from web.config file in asp.net, we need to add System.Configuration namespace that will help us to read our connection string.
Read Connectionstring in C#
string con = System.Configuration.ConfigurationManager.ConnectionStrings[“myDbConnection”].ConnectionString;
Read Connectionstring in Vb.net
Dim con As String = System.Configuration.ConfigurationManager.ConnectionStrings(“myDbConnection”).ConnectionString
Example: Simple Insert, Update and Delete in Asp.net
That’s it, now you’ll be able get connectionstring from web.config file and can use wherever you want.