Tuesday, August 17, 2010

Working with Configuration Files in C#

Configuration


A common issue when developing applications is how to retrieve configuration information, such as database connection strings, event log names, or other parameters.

The System.Configuration namespace provides the functionality for reading configuration files.

The location for application settings depends on the type of application you are creating. For web applications, settings are stored in the web.config, in console or WinForms gui applications, settings are stored in app.config file.

appSettings Section

An application configuration file follows a specific XML schema. The appSettings section is a predefined section of the configuration file designed to make it very easy to retrieve a value based on a given name. This is the easiest way to add application-specific settings into an application configuration file. The appSettings section of the configuration file consists of a series of "add" elements with "key" and "value" attributes.

Eg: Create a console application and add app.config file.

< configuration >< appSetting s>
< add key="SourceFile" value="d:\test\source.txt" / >
< add key="DestinationFile" value="d:\test\destination.txt" />
< /appSettings>
< / configuration >

--------

string source = ConfigurationSettings.AppSettings["SourceFile"];
string dest = ConfigurationSettings.AppSettings["DestinationFile"];
Console.WriteLine(source);
Console.WriteLine(dest);

Or

NameValueCollection nvc = ConfigurationManager.AppSettings;
Console.WriteLine(nvc["SourceFile"]);
Console.WriteLine(nvc["DestinationFile"]);

Eg:

< connectionStrings >
< add name="MyConnetion" providerName="System.Data.SqlClient" connectionString="data source=.\sqlexpress;initial catalog=MYDB;integrated security=true" / >
< / connectionStrings >

string constr = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
Console.WriteLine(constr);

Or

ConnectionStringSettingsCollection coll = ConfigurationManager.ConnectionStrings;
foreach (ConnectionStringSettings cs in coll)
{
if (cs.ProviderName == "System.Data.SqlClient")
{
Console.WriteLine(cs.ConnectionString);
}
}

No comments: