.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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Nilanka DharmadasaPosted Nov 9, 2009, 3:05 AM
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();
Nilanka DharmadasaPosted Nov 9, 2009, 2:47 AM
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. :)