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

Solution 1:

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.

Solution 2:

Clarification of previous answers...

  1. Add a new file to your project (AddNew ItemApplication Configuration File)

  2. The new configuration file will appear in Solution Explorer as App.Config.

  3. Add your settings into this file using the following as a template

    <configuration>
      <appSettings>
        <add key="setting1" value="key"/>
      </appSettings>
      <connectionStrings>
        <add name="prod" connectionString="YourConnectionString"/>
      </connectionStrings>
    </configuration>
    
  4. Retrieve them like this:

    private void Form1_Load(object sender, EventArgs e)
    {
        string setting = ConfigurationManager.AppSettings["setting1"];
        string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
    }
    
  5. When built, your output folder will contain a file called <assemblyname>.exe.config. This will be a copy of the App.Config file. No further work should need to be done by the developer to create this file.

Solution 3:

From a quick read of the previous answers, they look correct, but it doesn't look like anyone mentioned the new configuration facilities in Visual Studio 2008. It still uses app.config (copied at compile time to YourAppName.exe.config), but there is a UI widget to set properties and specify their types. Double-click Settings.settings in your project's "Properties" folder.

The best part is that accessing this property from code is typesafe - the compiler will catch obvious mistakes like mistyping the property name. For example, a property called MyConnectionString in app.config would be accessed like:

string s = Properties.Settings.Default.MyConnectionString;