我提出的方法是我覺得有點破綻,但太多的方法失敗了我需要繼續努力:-(
在運行新版本的情況下,我已經着手複製user.config的以前版本。
首先,確定是否需要升級,就像推薦此問題的很多變體一樣。
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
Version version = assembly.GetName().Version;
if (version.ToString() != Properties.Settings.Default.ApplicationVersion)
{
copyLastUserConfig(version);
}
然後,爲LINQ的最後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?)複製中得到PreviousSettingsDir中間。
它只是一個XML文件,對吧? – 2013-02-13 00:45:01
是的Jeremy這是Xml,這是我今天早上開始下的賽道。這是一個Xml文件,但是,每個新版本的應用程序都會在用戶配置文件的新文件夾中創建一個新的Xml文件。目前,我正在查找舊的Xml文件並正在讀取userSettings節點以實例化所有相關的設置對象。雖然感覺「哈克」,但我想知道是否有更好的方法。 (當我問到問題時,我還沒有開始這條賽道)。如果沒有更好的建議,我會發布結果。 – 2013-02-13 01:03:47
我認爲這是http://stackoverflow.com/questions/534261/how-do-you-keep-user-config-settings-across-different-assembly-versions-in-net(它有很多比在這裏接受的答案更好的答案)。 – 2014-06-16 16:49:11