Friday, July 23, 2010

Changing .NET App Properties/Settings at Runtime

Visual Studio* provides an application settings (aka properties) feature for console, library or windows applications. Creating and editing application settings at design time is straight-forward and can be managed conveniently thru VS's GUI.

But what if you need to change the settings at run-time? The answer is anything but obvious. The settings are contained in a class called "Settings," which derives from System.Configuration.ApplicationSettingsBase.  You could of course rewrite the code in the settings class, but then if you decide to make a change in VS's GUI all of your handiwork is immediately hosed.

There's one adjustment you can make directly in the GUI that puts you a step closer to your goal.  At the top of the Settings Designer screen, is a drop down box titled "Accessor Modifier."  There are two choices: the default is "Internal." The other choice is "Public." Choose "Public." As we'll see, this one alteration allows us to change the value of the properties in our code.

The application expects there to be a static property called Default, of type Settings, in the class Settings. Default, the only instance of Settings that will be acknowledged by the app, is created for you automatically by VS.  Default is essentially functioning as a singleton. Finally, ApplicationSettingsBase provides an indexer allowing us to reference the individual settings on Default.

Here's an example:

MyApp.Properties.Settings.Default["MyProperty"] = value;