.Settings file in Win Form App, Best Practice

2019-07-01 23:41发布

问题:

I have a Win Form app that stores some per user settings in a UserSettings.Settings file. This has worked well so far, however it seems that the Settings file gets "reset" when ever I release an update. Which I do through ClickOnce.

Is this the expected behavior?
Can I control if fields in the Settings file get overwritten?
Is there a better way I should store user settings?

Thanks

回答1:

When you release an update your updated app should call ApplicationSettingsBase.Upgrade Method to move values from the previous version. Here is a similar question: Automatically "upgrade" user settings from previous version of app.config file?

Keep in mind that you should call the above method only once so you probably will have to store whether you have already called Upgrade or not in the settings too and do something like this:

if(!Settings.Default.Upgraded)
{
   Settings.Default.Upgrade();
   Settings.Default.Upgraded = true;
   Settings.Default.Save();
}

Another possible solution is to store settings in a folder that does not depend on the application version. In that case you will not lose values and there will be no need to upgrade settings between versions.



回答2:

Where are you saving the .Settings file? It probably shouldn't be included in the installation directory with your executable. Try moving it to the user's application data directory:

http://blog.kowalczyk.info/article/Getting-user-specific-application-data-directory.html

Good luck!



回答3:

Are you simply using the built in Application Settings with ClickOnce?

If so then you just have to set the Scope to User in the settings editor and the setting will be merged on upgrades as described here

Just as each version of a ClickOnce application is isolated from all other versions, the application settings for a ClickOnce application are isolated from the settings for other versions as well. When your user upgrades to a later version of your application, application settings compares most recent (highest-numbered) version's settings against the settings supplied with the updated version and merges the settings into a new set of settings files.



回答4:

Under Windows Vista/7 It gets saved into:

C:\Users\USERNAME\AppData\Local\MANUFACTURER_NAME\

and

C:\Users\USERNAME\AppData\Roaming\MANUFACTURER_NAME\

im pretty sure it gets saved into the application data under xp too.

Your settings keep resetting because the new version uses a different folder. Check it.