How to persist changes in a .settings/.config file across a file version change?

坚强是说给别人听的谎言 提交于 2019-11-28 03:48:42
VoidDweller

Markus Olsson has already given a pretty good answer here.

Essentially you will need to use the ApplicationSettingsBase.Upgrade() method.

splattne

A few clarifications:

You have to call the Upgrade method of ApplicationSettingsBase derived class (that is normally called Settings and is created for you by Visual Studio):

Properties.Settings.Default.Upgrade();

When/where to call the Upgrade method? There is a simple trick you can apply: define a user setting called UpgradeRequired (example) as bool (the easiest way is through IDE). Make sure its default value is true.

Insert this code snipped at the start of the application:

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

So the Upgrade method will be called only after the version changes and only one time (since you disable further upgrades by setting UpgradeRequired = false until a version change - when the property regains default value of true).

I hope someone else has a better answer. I had this question a few years ago, and the only solution I could find (which did work) was to use my own mechanism for storing settings, rather than the default built-in .NET way.

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