54 lines
2.5 KiB
VB.net
54 lines
2.5 KiB
VB.net
Imports System
|
|
Imports System.Diagnostics
|
|
Imports System.IO
|
|
|
|
'只依赖 .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)
|
|
Dim Target = Path.GetFullPath(OldFileName)
|
|
Dim Source = Path.GetFullPath(NewFileName)
|
|
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"
|
|
Try
|
|
File.Copy(Source, Staged)
|
|
If File.Exists(Target) Then
|
|
File.Replace(Staged, Target, Target & ".bak", True)
|
|
Else
|
|
File.Move(Staged, Target)
|
|
End If
|
|
Finally
|
|
If File.Exists(Staged) Then File.Delete(Staged)
|
|
End Try
|
|
End Sub
|
|
End Module
|