Categories
Uncategorized

Read appsettings and connectionStrings from web.config file using c#

Ok, in this tutorial we are going to read appSetting and connectionStrings that are defined in web.config. 
For explanation’s sake lets have a sample web.config file first

<configuration>
<appSettings>
<add key="Mykey" value="Some Value" />
</appSettings>
<connectionStrings>
<add name="localConnStr" value="Data Source=ys2012;Initial Catalog=myDB;User ID=sa;Password=123;" />
</connectionStrings>
</configuration>

So in the above example I have defined 1 appSetting and 1 connectionString. Now below I have used the Configuration Manager Class to read appSettings as well as connectionStrings

1. Reading AppSetting

string value = ConfigurationManager.AppSettings["Mykey"].ToString();

2. Reading ConnectionString

string value = ConfigurationManager.ConnectionStrings["localConnStr"].ToString();