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
Recent Article
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
Related Article