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
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
- ModuleNotFoundError: No module named 'openpyxl' - Python
- How to get thumbnail from vimeo video URL in Python?
- Remove all special characters, punctuation except spaces from string - Python
- OSError: cannot write mode RGBA as JPEG- Python
- expected str, bytes or os.PathLike object, not JpegImageFile - Python
Related Article