.config
What is the important use of .config file? how give a database connection and how can access the databse from .config file? please give an example?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Nilanka DharmadasaRank #1,875 · 794 reputationPosted Nov 8, 2009, 9:47 PM EST
Let's take an example for this.
If you hard code your connection string, then when you want to deploy it at some other location, you should change your code, which means you have to compile your project again and this will add an unnessry cost.
So if you keep the connection string in your config file then, changing that file doesnt need any code change so you don't have to re compile your project.
Hope you got my point. In C# when you create a project, by default it adds a config file. You can define your settings in this file.
Let's say in your config file you have defined a setting like this.
<add key ="MySetting" value ="abc"/>
You can access this setting through your code and use it as you wish.
string text = System.Configuration.ConfigurationManager.AppSettings["MySetting"].ToString();
If my answer helps you please accept my answer. Otherwise let me know. :)
Nilanka DharmadasaRank #1,875 · 794 reputationPosted Nov 8, 2009, 10:05 PM EST
For your exact requirement,
Define you connection string in your config file. (App.config / Web.config ...)
Then from your code,
string ConnString = ConfigurationSettings.AppSettings["ConnectionString"].ToString();
SqlConnection cn = new SqlConnection(ConnString);
cn.Open();