当版本号更改时,如何升级user.config中的所有设置?

时间:2013-02-13 00:21:37

标签: c# winforms application-settings applicationsettingsbase

我有许多用户范围的设置由从ApplicationSettingsBase继承的对象存储在user.config中。

每个实例的 SettingsKey 是在运行时使用表单名称动态派生的。因此可能有数百个。

我已经阅读了很多问题和答案(就像这一个 - How do you keep user.config settings across different assembly versions in .net?),它们都建议在某些版本号检查中包装 ApplicationSettingsBase.Upgrade()

问题是(据我所知)你需要知道每一个* SettingsKey(用于实例化所有ApplicationSettingsBase对象的值,然后调用升级方法。

有没有办法一次升级所有user.config设置,或者替换,迭代文件中的所有设置进行升级?

1 个答案:

答案 0 :(得分:1)

我提出的方法是我认为的一种黑客行为,但是太多的方法都失败了,我需要继续做下去:-(

如果新版本正在运行,我已经使用了复制先前版本的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。