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

11

98

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?

Bhutan answered 22/9, 2008 at 12:25 Comment(2)
What's your version of .NET? For 2.0 and higher, there is a very cute way called Settings.Wit
@Seven it was a typo but it could mean "Explain with an example" :)Bhutan
S
136

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.

Scathing answered 22/9, 2008 at 12:29 Comment(7)
Actually it works in all versions of .NET, from v1.0 onwards. The new class in .NET 2.0 is ConfigurationManager.Prussianism
I personally use the "Settings" tab on the "Application Properties" (Framework 2.0 onwards only) because Visual Studio will code-gen strongly typed properties for your settings. They can also include "User" settings which are read/write at run time.Geranium
@Mike yeah i had a feeling that was the case, but I wasn't too sure. I have not worked much with 1.Scathing
Note the ConfigurationSettings is obsolete, use System.Configuration.ConfigurationManager.AppSettings["MyKey"];.Jemmie
Also a note, to use System.Configuration.ConfigurationManager your project needs a reference to System.Configuration.dllIrredeemable
You cannot modify the configuration settings at runtimeMarqueritemarques
What about versioning (simplest case being adding a new configuration item)? Will it break if using a configuration file created by the older version of the application?Horta
E
76

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.

Edwardedwardian answered 22/9, 2008 at 12:53 Comment(1)
This was useful to me. Two other points: When adding the new file to the project, the Application Configuration File was found when I clicked on the General node on the left side of the dialog. In order to use the ConfigurationManager class in my code, I had to add the System.Configuration DLL to my references.Invoke
A
29

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;
Aprilette answered 23/9, 2008 at 0:56 Comment(3)
This was available in VS2005.Celebration
Nice, but it (Project Properties | Settings) generates code that must be compiled. If you want to change a setting, you need to release new binaries to the customer.Juvenescent
@Juvenescent if these settings are in the "user" scope then you can change it programmatically, e.g. Settings.Default.Test = "abc"; Settings.Default.Save();Superfamily
N
10

You should create an App.config file (very similar to web.config).

You should right click on your project, add new item, and choose new "Application Configuration File".

Ensure that you add using System.Configuration in your project.

Then you can add values to it:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="setting1" value="key"/>
  </appSettings>
  <connectionStrings>
    <add name="prod" connectionString="YourConnectionString"/>
  </connectionStrings>
</configuration>

    private void Form1_Load(object sender, EventArgs e)
    {
        string setting = ConfigurationManager.AppSettings["setting1"];
        string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
    }

Just a note: According to Microsoft, you should use ConfigurationManager instead of ConfigurationSettings (see the remarks section):

"The ConfigurationSettings class provides backward compatibility only. For new applications you should use the ConfigurationManager class or WebConfigurationManager class instead. "

Narda answered 22/9, 2008 at 12:39 Comment(2)
Very helpful. Solved my issue to the T.Aglet
In Visual Studio 2015: Click on Project > Add Reference. Scroll down halfway to find System.Configuration Click OK, then update the line of code as per Nathan's comment.Alarice
P
7

The default name for a configuration file is [yourexe].exe.config. So notepad.exe will have a configuration file named notepad.exe.config, in the same folder as the program. This is a general configuration file for all aspects of the CLR and Framework, but it can contain your own settings under an <appSettings> node.

The <appSettings> element creates a collection of name-value pairs which can be accessed as System.Configuration.ConfigurationSettings.AppSettings. There is no way to save changes back to the configuration file, however.

It is also possible to add your own custom elements to a configuration file - for example, to define a structured setting - by creating a class that implements IConfigurationSectionHandler and adding it to the <configSections> element of the configuration file. You can then access it by calling ConfigurationSettings.GetConfig.

.NET 2.0 adds a new class, System.Configuration.ConfigurationManager, which supports multiple files, with per-user overrides of per-system data. It also supports saving modified configurations back to settings files.

Visual Studio creates a file called App.config, which it copies to the EXE folder, with the correct name, when the project is built.

Prussianism answered 22/9, 2008 at 12:46 Comment(0)
K
6

The best (IMHO) article about .NET Application configuration is on CodeProject, Unraveling the Mysteries of .NET 2.0 Configuration. And my next favorite (shorter) article about sections in the .NET configuration files is Understanding Section Handlers - App.config File.

Katzman answered 22/9, 2008 at 12:30 Comment(1)
It really isn't not the simplest way asked by the user, but Unraveling the mysteries of .NET 2.0 configurations are really a great series of articles.Loris
G
3

In Windows Forms, you have the app.config file, which is very similar to the web.config file. But since what I see you need it for are custom values, I suggest using Settings.

To do that, open your project properties, and then go to settings. If a settings file does not exist you will have a link to create one. Then, you can add the settings to the table you see there, which would generate both the appropriate XML, and a Settings class that can be used to load and save the settings.

The settings class will be named something like DefaultNamespace.Properties.Settings. Then, you can use code similar to:

using DefaultNamespace.Properties;

namespace DefaultNamespace {
    class Class {
        public int LoadMySettingValue() {
            return Settings.Default.MySettingValue;
        }
        public void SaveMySettingValue(int value) {
            Settings.Default.MySettingValue = value;
        }
    }
}
Gadabout answered 22/9, 2008 at 12:33 Comment(0)
E
2

I agree with the other answers that point you to app.config. However, rather than reading values directly from app.config, you should create a utility class (AppSettings is the name I use) to read them and expose them as properties. The AppSettings class can be used to aggregate settings from several stores, such as values from app.config and application version info from the assembly (AssemblyVersion and AssemblyFileVersion).

Eosin answered 22/9, 2008 at 13:17 Comment(0)
M
2

A very simple way of doing this is to use your your own custom Settings class.

Mika answered 1/3, 2009 at 2:25 Comment(1)
+1 for the less verbose link to ApplicationSettings at msdn.microsoft.com/en-us/library/… which seems simpler than ConfigurationManager implementations. Get/set settings, don't care about "XML Shaping".Evangelineevangelism
C
1

Use:

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

AppSettings has been deprecated and is now considered obsolete (link).

In addition, the appSettings section of the app.config has been replaced by the applicationSettings section.

As someone else mentioned, you should be using System.Configuration.ConfigurationManager (link) which is new for .NET 2.0.

Carbonic answered 22/9, 2008 at 12:25 Comment(1)
ConfigurationSettings is deprecated not AppSettings.Elaterin
U
0

What version of .NET and Visual Studio are you using?

When you created the new project, you should have a file in your solution called app.config. That is the default configuration file.

Umbel answered 22/9, 2008 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.