174

When developing a .NET Windows Forms Application we have the choice between those App.config tags to store our configuration values. Which one is better?

<configuration>

  <!-- Choice 1 -->
  <appSettings>
    <add key="RequestTimeoutInMilliseconds" value="10000"/>
  </appSettings>

  <!-- Choice 2 -->
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5612342342" >
        <section name="Project1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5612342342" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <applicationSettings>
    <Project1.Properties.Settings>
      <setting name="TABLEA" serializeAs="String">
        <value>TABLEA</value>
      </setting>
    </Project1.Properties.Settings>
  </applicationSettings>

</configuration>
Matt
  • 25,467
  • 18
  • 120
  • 187
Jader Dias
  • 88,211
  • 155
  • 421
  • 625
  • In MS example code they use appSettings http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx this I find confusing :( – Hunt Feb 03 '12 at 11:59
  • 1
    Found this article http://www.codeproject.com/KB/files/SaveConnStringInAppConfig.aspx?q=working+with+applicationsettings+c%23 it seems to imply that appSettings are for w/r an the applicationSettings are for read only. – Hunt Feb 11 '12 at 15:11
  • Another article that is relevant http://stackoverflow.com/questions/453161/best-practice-to-save-application-settings-in-a-windows-application – Hunt Feb 11 '12 at 15:34
  • **Note** that the same is applicable to the web.config, so I added the web.config tag to this question. – Matt Dec 05 '16 at 10:24

6 Answers6

155

The basic <appSettings> is easier to deal with - just slap in a <add key="...." value="..." /> entry and you're done.

The downside is: there's no type-checking, e.g. you cannot safely assume your number that you wanted to configure there really is a number - someone could put a string into that setting..... you just access it as ConfigurationManager["(key)"] and then it's up to you to know what you're dealing with.

Also, over time, the <appSettings> can get rather convoluted and messy, if lots of parts of your app start putting stuff in there (remember the old windows.ini file? :-)).

If you can, I would prefer and recommend using your own configuration sections - with .NET 2.0, it's really become quite easy, That way, you can:

  • a) Define your configuration settings in code and have them type-safe and checked
  • b) You can cleanly separate YOUR settings from everyone else's. And you can reuse your config code, too!

There's a series of really good articles on you to demystify the .NET 2.0 configuration system on CodeProject:

  1. Unraveling the mysteries of .NET 2.0 configuration

  2. Decoding the mysteries of .NET 2.0 configuration

  3. Cracking the mysteries of .NET 2.0 configuration

Highly recommended! Jon Rista did a great job explaining the configuration system in .NET 2.0.

Luis
  • 5,786
  • 8
  • 43
  • 62
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    I find applicationSettings easier to add edit and remove settings plus you don't have to write a line of code, plus they are type safe, plus you can scope them to user or application, because you can just use the Settings tab in your project's properties in VS. – markmnl May 12 '14 at 06:49
20

Application settings can be controlled from a designer (there is usually a Settings.settings file by default) so its easier to modify and you can access them programmatically through the Settings class where they appear like a strongly typed property. You can also have application and user level settings, as well as default settings for rolling back.

This is available from .NET 2.0 onwards and deprecates the other way of doing it (as far as I can tell).

More detail is given at: msdn.microsoft.com/en-us/library/k4s6c3a0.aspx

John Smith
  • 7,243
  • 6
  • 49
  • 61
Peter C
  • 2,257
  • 2
  • 25
  • 28
16

To understand the pros and cons of settings in the app.config, I suggest that you look into the technical details of both. I have included links where you can find source code for handling, describing more technical details below.

Let me briefly summarize what I recognized when I worked with them (note: the same is applicable to the web.config file of a web site / web application):


applicationSettings in .NET
(click above to view source code and technical details)


Pros

  • They allow to store typed data, including object types (via serializeAs property)

  • They have a user and application scope, allowing to store default values

  • They are supported in Visual Studio's configuration section

  • Long strings and/or data with special characters are very well supported (for example, embedded JSON strings containing double quotes)


Cons

  • User settings are stored in a different place in the user profile (with a cryptic path), can be difficult to clean up

  • Application scope settings are read-only during runtime of the application (only user scope settings can be changed during runtime)

  • Read / Write methods code built by Visual Studio's settings designer, not directly provided by 3rd party tools (see link above for a workaround solution)


AppSettings in .NET
Update: AppSettings in .NET Core
(click above to view source code and technical details)


Pros

  • Are "light-weight", i.e. easy to handle

  • Read and write access during runtime of the application

  • They can be edited easily by Administrators in the
    Internet Information Services (IIS) Manager
    (Features View -> Application Settings, note that the name of the icon is misleading since it can only handle AppSettings and not ApplicationSettings)


Cons

  • Support only string data; string length and special characters are limited

  • They don't have a user scope

  • They don't support default values

  • Are not directly supported in Visual Studio's configuration section


Matt
  • 25,467
  • 18
  • 120
  • 187
13

I've been using a pattern I found a while back where you use basic xml tags but wrap the settings in a static config class. So - a DIY App.Settings.

DotNetPearls Static Config Pattern

If you do it this way you can:

  • use different sets of config values for different environments (dev, test, prod)
  • provide for sensible defaults for each setting
  • control how values are defined and instantiated

It's tedious to set up but performs well, hides references to key names, and is strongly typed. This kind of pattern works well for config that isn't changed by the application, although you could probably work in support for changes as well.

Config:

<add key="machineName" value="Prod" />
<add key="anotherMachineName" value="Test" />
<add key="EnvTypeDefault" value="Dev" />

<add key="RootURLProd" value="http://domain.com/app/" />
<add key="RootURLTest" value="http://test.domain.com/app/" />
<add key="RootURLDev" value="http://localhost/app/" />

<add key="HumanReadableEnvTypeProd" value="" />
<add key="HumanReadableEnvTypeTest" value="Test Mode" />
<add key="HumanReadableEnvTypeDev" value="Development Mode" />

Config class:

using System;
using System.Collections.Generic;
using System.Web;
using WebConfig = System.Web.Configuration.WebConfigurationManager;

    public static class Config
    {
        #region Properties

        public static string EnvironmentType { get; private set; }

        public static Uri RootURL { get; private set; }

        public static string HumanReadableEnvType { get; private set; }

        #endregion

        #region CTOR

        /// <summary>
        /// Initializes all settings when the app spins up
        /// </summary>
        static Config()
        {
            // Init all settings here to prevent repeated NameValueCollection lookups
            // Can increase performance on high volume apps

            EnvironmentType =
                WebConfig.AppSettings[System.Environment.MachineName] ??
                "Dev";

            RootURL =
                new Uri(WebConfig.AppSettings["RootURL" + EnvironmentType]);

            HumanReadableEnvType =
                WebConfig.AppSettings["HumanReadableEnvType" + Config.EnvironmentType] ??
                string.Empty;
        }

        #endregion
    }
HAL9000
  • 1,002
  • 2
  • 17
  • 28
9

I like working with the simpler version for storing and accessing single values.

<appSettings>
    <add key="MyConfigKey" value="true"/>
</appSettings>

I wrote a utility class to access values in a typesafe way that allows for default values. If defaults are not provided, then helpful exception messages are given.

You can see/download the class here:

http://www.drewnoakes.com/code/util/app-settings-util/

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 3
    +1, it's simpler especially if you have multiple assemblies (settings typically have a section per assembly). I have a similar helper class. BTW your class currently expects the config file to use culture-sensitive strings which is not a good thing - e.g. should be "Double.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out result)" rather than "Double.TryParse(s, out result)". Also to nitpick, the MS coding guidelines recommend GetInt32, GetInt16, GetBoolean rather than GetInt, GetShort, GetBool. – Joe Jun 08 '09 at 07:12
  • That's fine, but does not answer the question about pro's and cons of AppSettings. – Matt Feb 06 '18 at 14:39
  • @Matt, the pro is that it's simpler. The con is that it's simpler. If you only need a couple of literal values (bools, ints, string, etc) then this approach gives the most bang for the buck. If you need structured data, namespace separation, XSD supported validation/completion, etc, then a custom section might be a better fit. Another option is to ignore the `App.config` file altogether and use your own configuration file. Plenty of libraries do that. NLog comes to mind. – Drew Noakes Feb 07 '18 at 11:25
  • @DrewNoakes - I agree with you. Thanks for the clarification. – Matt Feb 07 '18 at 11:27
2

One big benefit of using ApplicationSettings is when the application is deployed through ClickOnce as explained in detailed on this page.

Basically, if a setting is of type User and has been modified from its default value, it will stay modified from update to update. If a setting is of type Application, it will be automatically overridden when the application is updated.

Also, in VB.NET, ApplicationSettings may be accessed by Simply using My.Settings. making it the simplest settings proposition available from a GUI point of view.

bkqc
  • 831
  • 6
  • 25