How to get connection string from web config configuration in asp.net c#?

How to get connection string from web config configuration in asp.net c#?, someone asked me to explain?

asp net connection string example

In this article, I will show you how to get string connection from web.config file in asp.net using c#. Two ways to write the connection string in web.config file as,

1. Write inside the <ConnectionString> </ConnectionString> in web config configuration file.

2.Also, you can write inside <appSettings></appSettings>.

First way,

<connectionStrings>

    <add name="foo" providerName="System.Data.SqlClient" connectionString="Data Source=BIG-PC;

Initial Catalog=DataBaseName;User Id=****;Password=*****" />

</connectionStrings>

We can access the database using the connection string, here we are assigned to a string variable using ConfigurationManager c# class.

Reading connection string from ConnectionString,

protected void Page_Load(object sender, EventArgs e)

        {

            string conn = System.Configuration.ConfigurationManager.AppSettings["MySQLConnection"];

        }

Second Way,

<appSettings>

    <add key="MySQLConnection" value="Data Source=ServerName;Integrated Security=true;

Initial Catalog=DataBaseName;User Id=****,User;Password=*****" />  </appSettings>

We can also get  get connection string from the appSettings of web config file in asp.net c#.

Reading connection string from appSettings,

     protected void Page_Load(object sender, EventArgs e)

        {

            string constr = ConfigurationManager.ConnectionStrings["foo"].ToString();

        }

For both, we need to import System.configuration namespace for reading connection string from web.config file.

Post your comments / questions