Imports System Imports System.Diagnostics Imports System.IO Imports System.Security.Cryptography Imports System.Threading '只依赖 .NET,供启动器与独立的更新功能测试共同使用。 Public Module ModLauncherUpdate Public Function ParseLauncherVersion(Value As String) As Version If String.IsNullOrWhiteSpace(Value) Then Return Nothing Dim Clean = Value.Trim().TrimStart("v"c, "V"c) Dim Separator = Clean.IndexOfAny(New Char() {"-"c, "+"c}) If Separator >= 0 Then Clean = Clean.Substring(0, Separator) Dim Parts = Clean.Split("."c) If Parts.Length <> 3 Then Return Nothing Dim Numbers(2) As Integer For Index = 0 To 2 If Not Integer.TryParse(Parts(Index), Globalization.NumberStyles.None, Globalization.CultureInfo.InvariantCulture, Numbers(Index)) Then Return Nothing Next Return New Version(Numbers(0), Numbers(1), Numbers(2), 0) End Function Public Sub ReplaceLauncherFile(ProcessId As Integer, OldFileName As String, NewFileName As String, Optional WaitTimeout As Integer = 30000, Optional Operations As LauncherUpdateFileOperations = Nothing) Dim Target = Path.GetFullPath(OldFileName) Dim Source = Path.GetFullPath(NewFileName) If Operations Is Nothing Then Operations = New LauncherUpdateFileOperations() If WaitTimeout < 0 Then Throw New ArgumentOutOfRangeException("WaitTimeout") If String.Equals(Target, Source, StringComparison.OrdinalIgnoreCase) Then Throw New IOException("更新文件与目标文件不能相同") If Not File.Exists(Source) Then Throw New FileNotFoundException("找不到已下载的更新文件", Source) If ProcessId > 0 Then If ProcessId = Process.GetCurrentProcess().Id Then Throw New InvalidOperationException("更新进程不能替换自身") Dim Previous As Process = Nothing Try Previous = Process.GetProcessById(ProcessId) Catch ex As ArgumentException '旧进程已经退出。 End Try If Previous IsNot Nothing Then Using Previous If Not Previous.WaitForExit(WaitTimeout) Then Throw New TimeoutException("启动器尚未退出,请关闭后重试更新") End Using End If End If '先验证下载副本和旧文件备份,再删除并复制;任何复制或校验失败都尝试恢复旧文件。 Dim Staged = Target & "." & Guid.NewGuid().ToString("N") & ".new" Dim Backup = Target & ".bak" Dim OriginalHash As String = Nothing Dim BackupReady = False Dim ReplacementStarted = False Try Dim NewHash = GetLauncherFileHash(Source) RetryLauncherFileOperation(Sub() Operations.CopyFile(Source, Staged, True), Operations) If GetLauncherFileHash(Staged) <> NewHash Then Throw New IOException("更新暂存文件的 SHA256 校验失败") If File.Exists(Target) Then OriginalHash = GetLauncherFileHash(Target) RetryLauncherFileOperation(Sub() Operations.CopyFile(Target, Backup, True), Operations) If GetLauncherFileHash(Backup) <> OriginalHash Then Throw New IOException("旧版本备份的 SHA256 校验失败,已停止更新") BackupReady = True End If ReplacementStarted = True RetryLauncherFileOperation(Sub() Operations.DeleteFile(Target), Operations) RetryLauncherFileOperation(Sub() Operations.CopyFile(Staged, Target, True), Operations) If GetLauncherFileHash(Target) <> NewHash Then Throw New IOException("替换后的启动器 SHA256 校验失败") Catch UpdateError As Exception If Not ReplacementStarted Then Throw Try If BackupReady Then RetryLauncherFileOperation(Sub() Operations.CopyFile(Backup, Target, True), Operations) If GetLauncherFileHash(Target) <> OriginalHash Then Throw New IOException("恢复后的旧程序 SHA256 校验失败") Else '首次写入失败时,移除不完整的目标文件。 RetryLauncherFileOperation(Sub() Operations.DeleteFile(Target), Operations) End If Catch RestoreError As Exception Throw New AggregateException("更新失败,自动恢复也未完成。请保留下载文件,并从备份手动恢复:" & Backup, New Exception() {UpdateError, RestoreError}) End Try Throw New IOException(If(BackupReady, "更新失败,旧程序已恢复:", "更新失败,未保留不完整的程序:") & UpdateError.Message, UpdateError) Finally Try If File.Exists(Staged) Then Operations.DeleteFile(Staged) Catch CleanupError As Exception '暂存文件清理失败不能掩盖替换或恢复的真实结果。 Trace.TraceWarning("清理更新暂存文件失败:" & CleanupError.Message) End Try End Try End Sub Private Sub RetryLauncherFileOperation(Operation As Action, Operations As LauncherUpdateFileOperations) Dim Timer = Stopwatch.StartNew() Do Try Operation() Return Catch ex As Exception When TypeOf ex Is IOException OrElse TypeOf ex Is UnauthorizedAccessException If Timer.ElapsedMilliseconds >= Operations.RetryTimeoutMilliseconds Then Throw Thread.Sleep(100) End Try Loop End Sub Private Function GetLauncherFileHash(FileName As String) As String Using Algorithm = SHA256.Create() Using Stream = File.OpenRead(FileName) Return BitConverter.ToString(Algorithm.ComputeHash(Stream)) End Using End Using End Function Public Function GetLauncherUpdateResultPath(TargetPath As String) As String Return Path.Combine(Path.GetDirectoryName(Path.GetFullPath(TargetPath)), "PCL", "UpdateResult-" & Path.GetFileName(TargetPath) & ".json") End Function End Module '文件操作单独封装,使恢复流程可以在隔离目录内模拟真实的 I/O 失败。 Public Class LauncherUpdateFileOperations Public Property RetryTimeoutMilliseconds As Integer = 5000 Public Overridable Sub CopyFile(Source As String, Target As String, Overwrite As Boolean) File.Copy(Source, Target, Overwrite) End Sub Public Overridable Sub DeleteFile(Target As String) File.Delete(Target) End Sub End Class Public Class LauncherUpdateResult Public Property Succeeded As Boolean Public Property TargetPath As String Public Property DownloadPath As String Public Property BackupPath As String Public Property VersionName As String Public Property ErrorMessage As String Public Property HelperProcessId As Integer Public Property CompletedUtc As Date End Class