.NET Application Settings

2011, Sep 02    

Application Settings are the recommended way to save state between runs of your program. Long gone are the days of using the registry or INI files to save information. The only problem with Application Settings though is that they tend to disappear whenever you release a new version of your application. Fortunately, it is easy to fix this with some boiler plate code.

First, we need to make sure that our project has a settings file. It is usually under the Properties node of the project. If it is not, right click on the solution and Add | New Item¦ | Visual C# Items | General | Settings File and name it Settings.settings. Next, drag it and drop it in your project's Properties folder.

Next, you need to add a bool User setting called UpgradeRequired and default it to true. Next, at the very beginning of your Main, you check if UpgradeRequired is true, and if it is, upgrade the settings, set UpgradeRequired to false and save out the settings. This will pull in the settings from previous versions of your application.

Your settings should look like this,

settings

The code should look like this,

static void Main( string[] args )
{
   // Upgrade settings if required
   if ( Properties.Settings.Default.UpgradeRequired )
   {
      Properties.Settings.Default.Upgrade();
      Properties.Settings.Default.UpgradeRequired = false;
      Properties.Settings.Default.Save();
   }

   // Do work...

   // At the end of main, save out any changes to settings
   Properties.Settings.Default.Save();
}</code>

Now you just need to create new settings and use them in your application. Any setting with Application scope will be set in your app.config and will be read-only. This is often used for connection strings and other information that is unlikely to change. User scoped settings also have their default values in app.config, but any changes are written out to an XML file in the user's AppData folder.

Also, notice that code gets generated for any setting that you create and you access it through a property on Properties.Settings.Default. You can use any complex type for a setting, including classes in your application, as long as they are Serializable.