Simplest way to have a configuration file in a Windows Forms C# application

Fabio Gomes picture Fabio Gomes · Sep 22, 2008 · Viewed 229k times · Source

I'm really new to .NET, and I still didn't get the hang about how configuration files work.

Every time I search on Google about it I get results about web.config, but I'm writing a Windows Forms application.

I figured out that I need to use the System.Configuration namespace, but the documentation isn't helping.

How do I define that my configuration file is XYZ.xml? Or does it have a "default" name for the configuration file? I still didn't get that.

Also, how do I define a new section? Do I really need to create a class which inherits from ConfigurationSection?

I would like to just have a configuration file with some values like this:

<MyCustomValue>1</MyCustomValue>
<MyCustomPath>C:\Some\Path\Here</MyCustomPath>

Is there a simple way to do it? Can you explain in a simple way how to read and write from/to a simple configuration file?

Answer

qui picture qui · Sep 22, 2008

You want to use an App.Config.

When you add a new item to a project there is something called Applications Configuration file. Add that.

Then you add keys in the configuration/appsettings section

Like:

<configuration>
 <appSettings>
  <add key="MyKey" value="false"/>

Access the members by doing

System.Configuration.ConfigurationSettings.AppSettings["MyKey"];

This works in .NET 2 and above.