我想出的方法有点像我觉得的黑客,但是太多的方法都失败了,我需要继续做下去:-(
在运行新版本的情况下,我不得不复制以前版本的 user.config。
首先,确定是否需要升级,就像这个问题推荐的许多变体一样。
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
Version version = assembly.GetName().Version;
if (version.ToString() != Properties.Settings.Default.ApplicationVersion)
{
copyLastUserConfig(version);
}
然后,复制最后一个 user.config....
private static void copyLastUserConfig(Version currentVersion)
{
try
{
string userConfigFileName = "user.config";
// Expected location of the current user config
DirectoryInfo currentVersionConfigFileDir = new FileInfo(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath).Directory;
if (currentVersionConfigFileDir == null)
{
return;
}
// Location of the previous user config
// grab the most recent folder from the list of user's settings folders, prior to the current version
var previousSettingsDir = (from dir in currentVersionConfigFileDir.Parent.GetDirectories()
let dirVer = new { Dir = dir, Ver = new Version(dir.Name) }
where dirVer.Ver < currentVersion
orderby dirVer.Ver descending
select dir).FirstOrDefault();
if (previousSettingsDir == null)
{
// none found, nothing to do - first time app has run, let it build a new one
return;
}
string previousVersionConfigFile = string.Concat(previousSettingsDir.FullName, @"\", userConfigFileName);
string currentVersionConfigFile = string.Concat(currentVersionConfigFileDir.FullName, @"\", userConfigFileName);
if (!currentVersionConfigFileDir.Exists)
{
Directory.CreateDirectory(currentVersionConfigFileDir.FullName);
}
File.Copy(previousVersionConfigFile, currentVersionConfigFile, true);
}
catch (Exception ex)
{
HandleError("An error occurred while trying to upgrade your user specific settings for the new version. The program will continue to run, however user preferences such as screen sizes, locations etc will need to be reset.", ex);
}
}
感谢Allon Guralnek对这个问题的回答(How do you upgrade Settings.settings when the stored data type changes?)中间的 Linq 获得了 PreviousSettingsDir。