ConnectionStrings and AppSettings value from config file. ( c# / .NET)
We have faced the issues and difficulties of hard coded strings and values in our application several times. Keys, connection strings, user credentials and other dynamic settings are not supposed to be hard coded during application development. If done so, they can causes many limitations to our application and even small changes might require recompilation of application and several human hours for development and deployment.
Hence, in our application, we can put these dynamic settings in a config file and read it from there. In .net, We have a library System.Configuration to read these settings and connection strings. Below you can find the code implementation of config file as well as the library in c#.
Code implementation in config file :
<connectionStrings>
<add name="_NameOfConnectionString_" connectionString="_ConnectionString_" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="_key1Name_" value="123" />
<add key="_key2Name_" value="abc" />
</appSettings>
To access these configuration values in our code, we can write our code as following.
Code implementation in class file :
using System.Configuration;
// you can access the appsettings in your code like below
string key1Value = ConfigurationManager.AppSettings["_key1Name_"];
string key2value = ConfigurationManager.AppSettings["_key2Name_"];
// you can access the connection string in your code like below
string connectionstring = ConfigurationManager.ConnectionStrings["_NameOfConnectionString_"].ToString();
I found worthful to follow your blog...awesome!!
ReplyDelete