How do you keep user.config settings across different assembly versions in .net?

Basically the problem is that each time the assembly version changes (i.e. the user installs a new version of the application) all their settings are reset the the defaults (or more accurately a new user.config file is created in a folder with a different version number as the name)

How can I keep the same settings when upgrading versions, since using ini files or the registry seem to be discouraged?

When we used Clickonce it seemed to be able to handle this, so it seems like it should be able to be done, but I'm not sure how.


Solution 1:

ApplicationSettingsBase has a method called Upgrade which migrates all settings from the previous version.

In order to run the merge whenever you publish a new version of your application you can define a boolean flag in your settings file that defaults to true. Name it UpgradeRequired or something similar.

Then, at application start you check to see if the flag is set and if it is, call the Upgrade method, set the flag to false and save your configuration.

if (Settings.Default.UpgradeRequired)
{
    Settings.Default.Upgrade();
    Settings.Default.UpgradeRequired = false;
    Settings.Default.Save();
}

Read more about the Upgrade method at MSDN. The GetPreviousVersion might also be worth a look if you need to do some custom merging.

Solution 2:

The next short solution works for me when we need to upgrade only once per version. It does not required additional settings like UpgradeRequired:

if (!ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).HasFile)
    Settings.Default.Upgrade();

Solution 3:

I know it's been awhile... In a winforms app, just call My.Settings.Upgrade() before you load them. This will get the latest settings, whether the current version or a previous version.