July 2, 2008

Visual Studio Project Settings

When I first started using the settings feature that was built into Visual Studio, I thought that they were pretty straight forward. It turns out that I had virtually no idea what was really going on. This is probably has mostly to do with MSDN's lack of documentation, as usual. Now I will attempt to lay out how this monster really works.

First goto the properties page of a project and goto the settings tab. From here you can set up either Application or User settings. It turns out that the differences are pretty self explanitory. A user setting will actually end up in a user.config file burried in the Documents And Settings folder for each user. This means that each user will be able to have a different set of settings for these. Application settings are actually read from the myapp.exe.config file in the application path (usually in Program Files).

To access these settings from code, all you need to do is:

string mySetting = Properties.Settings.Default.MySetting;

If you are accessing a user setting, the program will first look in the user.config file burried in the user's Documents And Settings, then in the myApp.exe.config file, and finally in the hardcoded default values. For an application setting, the same order is used starting at the myApp.exe.config file.

To add to the excitement, it turns out that it is only possible to save user settings from your application. If you are writing to a user setting to the user.config file in the user's Documents And Settings, all you have to do is:

Properties.Settings.Default.MySetting = mySetting;
Properties.Settings.Default.Save();

If you want to save a user setting or an application setting to the myApp.config file in the application's path, there is no built in way. You will have to resort to loading the file into an XML DOM API and edit the file manually.

The main point to recognize here is that even if you uninstall an application, the user settings will stick around in the Application Data for a user, and magically reappear next time the application is installed. These files must be removed if you want to reset your user settings.

No comments: