Keep user's settings after altering assembly/file version

℡╲_俬逩灬. 提交于 2019-11-28 05:53:44

Use the built in Settings classes, you just need to upgrade the settings anytime you change the application version. Here's how to do it: In the Settings.settings file, create a new setting UpdateSettings type=bool Scope=User Value=True

Include the following code before you use any Settings (it can run every time the app runs, as this makes running in debugger easier too)

// Copy user settings from previous application version if necessary
if (MyApp.Properties.Settings.Default.UpdateSettings)
{
    MyApp.Properties.Settings.Default.Upgrade();
    MyApp.Properties.Settings.Default.UpdateSettings = false;
    MyApp.Properties.Settings.Default.Save();
}

When your new application version is run UpdateSettings will have a default value of True and none of your old settings will be used. If UpdateSettings is true we upgrade the settings from the old settings and save then under the new app version.

Here's how I solved it.

In the GUI application it is very easy to restore the settings by executing

Properties.Settings.Default.Upgrade ();
Properties.Settings.Default.Reload ();
Properties.Settings.Default.NewVersionInstalled = false;
Properties.Settings.Default.Save ();

However, I've always had the problem that all other libraries lost their settings when a new version has been installed. With the following implementation the software runs through all assemblies of the AppDomain and restores the settings of the respective library:

foreach(var _Assembly in AppDomain.CurrentDomain.GetAssemblies())
{
    foreach(var _Type in _Assembly.GetTypes())
    {
        if(_Type.Name == "Settings" && typeof(SettingsBase).IsAssignableFrom(_Type))
        {
            var settings = (ApplicationSettingsBase)_Type.GetProperty("Default").GetValue(null, null);
            if(settings != null)
            {
                settings.Upgrade();
                settings.Reload();
                settings.Save();
            }
        }
    }
}

I've implemented the code in the App.xaml.cs of the GUI project and it will always be executed when the setting "NewVersionInstalled" was set to true by a new version.

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!