2014-01-11

How to Keep Settings from a Previous Install

I have a WPF program that is frequently updated from the Internet. There are settings created by the program and stored using Properties.Settings.Default.SettingName. However, after the user re-runs the InstallShield setup program, the old settings were getting overwritten with the defaults. Normally, the .NET Framework notices that this is not the same version as the previous one, and ignores the old .Config file that stores the settings and reverts to the default.
It turns out that this is trivial to fix. Just add the line below as the first thing your program does. In WPF, a good place is in the App.xaml.cs file.

namespace Example
{
    static App()
    {
        Example.Properties.Settings.Default.Upgrade();
    }
}

This causes the .NET Framework to load the old settings, even though the version number has changed. This method comes from the ApplicationSettingsBase.Upgrade() method.
There is a problem, though. You only want to run this once, because otherwise it will always load the settings from the previous version, even if you make changes. You can fix that by creating a property called FirstRun as a boolean with a default value of true. Then use this code:

namespace Example
{
    static App()
    {
        if (Example.Properties.Settings.Default.FirstRun)
        {
            Example.Properties.Settings.Default.Upgrade();
            Example.Properties.Settings.Default.FirstRun = false;
            Example.Properties.Settings.Default.Save();
        }
    }
}

No comments :

Post a Comment