3

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

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

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

问题是(据我所知)您需要知道用于实例化所有 ApplicationSettingsBase 对象以依次调用升级方法的每个 *SettingsKey( 值。

有没有办法一次升级所有 user.config 设置,或者迭代文件中的所有设置来升级它们?

4

1 回答 1

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。

于 2013-02-13T02:26:09.627 回答