jump to navigation

Configuring an application January 14, 2006

Posted by Christian López Espínola in CSharp, Programming, xml.
6 comments

At first, sorry for posting so late, I didn’t forgot you. Today we’re going to make easy configuring our applications.
We need a file in our project called “App.config”, which will contain all our application parameters. This is a XML file, with the following format:


<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="settingName" value="settingValue"/>
<add key=�anotherSettingName� value=�anotherSettingValue�/>
[more...]
<add key=�Height� value=�200�/>
<add key=�Width� value=�500�/>
<add key=�FormTitle� value=�Hello World�/>
</appSettings>
</configuration>

If you use VS .NET 2005, right click at your project, Add a new item and select Application Configuration File will generate the file “App.config” automatically.

Now in our application we import the System.Configuration namespace, located at the System.dll assembly.
We must use an instance of AppSettingsReader class.


public class MyClass : System.Windows.Forms.Form
{
private AppSettingsReader configReader = new AppSettingsReader();
[...]
}

The AppSettingsReader class implements a method with the following prototype:


object GetValue(string key, Type type)

For example, we will make a Windows Form and configure it like follows (we can make it at the constructor or at InitializeComponent method):


this.Text = (string)configReader.GetValue(“FormTitle�, typeof(string));
this.Height = (int)configReader.GetValue(“Height�,typeof(int));
this.Width = (int)configReader.GetValue(“Width�,typeof(int));

Finally… build and execute! Change values at “App.config” and execute again!