Upgrading Settings files when changing application version






4.20/5 (3 votes)
If (like me) you use the Assembly version of your EXE to handle versioning, and you (like me) use the Settings.Settings for configuration items, then you've probably noticed the config is lost when the version is changed.
Introduction
When you change the Assembly version, the next load from the configuration data will come back with default values - because the version has been changed and .NET isn't sure the config will be valid. For users, this is either annoying, or harmful depending on what information you choose to store. This Tip provides a simple solution to keeping existing configuration.
Using the code
Add a new Setting to your assembly, call it ApplicationSettingsVersion
, make it a string, leave it User, and leave the default value blank.
Paste the code into your main Form constructor, above any configuration access.
// Prevent need to lose config settings on upgrade.
// Note: You cannot put this code into a utilities
// DLL - it gets the version of the Assembly that
// the code is running in - which is what we need
// as the utilities DLL could have it's own settings...
string thisVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
if (Properties.Settings.Default.ApplicationSettingsVersion != thisVersion)
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.ApplicationSettingsVersion = thisVersion;
}
As the comments say: you can't move this to a utility assembly, and call the method, because you want to upgrade the settings for the main EXE file - and while you could use GetEntryAssembly
instead of GetExecutingAssembly
to get the correct Assembly, it would affect the wrong settings, as the DLL could have it's own, separate settings file - mine do for common utility look-and-feel.
You need to execute this code in each Assembly with it's own settings.
History
Original Version