73 lines
2.6 KiB
VB.net
73 lines
2.6 KiB
VB.net
Imports System.IO
|
|
Imports System.Net
|
|
Imports System.Web
|
|
|
|
Public Class Updater
|
|
'Private Shared ReadOnly localPath As String = Application.ExecutablePath
|
|
Private Shared ReadOnly tempPath As String = Path.Combine(Path.GetTempPath(), "update_temp.exe")
|
|
Private Shared ReadOnly vbsPath As String = Path.Combine(Path.GetTempPath(), "update_script.vbs")
|
|
|
|
''' <summary>
|
|
''' 开始更新任务
|
|
''' </summary>
|
|
''' <param name="localPath">目标地址</param>
|
|
''' <param name="updateUrl">更新文件地址</param>
|
|
''' <returns></returns>
|
|
Public Shared Async Function StartUpdateAsync(localPath As String, updateUrl As String) As Task
|
|
Try
|
|
' 下载更新文件
|
|
Using client As New WebClient()
|
|
Await client.DownloadFileTaskAsync(updateUrl, tempPath)
|
|
Logger.Info(updateUrl & "文件下载完毕")
|
|
End Using
|
|
|
|
' 创建 VBS 脚本 (修正了 VBScript 语法错误)
|
|
Dim vbsContent As String = $"
|
|
Set WshShell = CreateObject(""WScript.Shell"")
|
|
WScript.Sleep 4000
|
|
|
|
' 解除保护并替换 EXE
|
|
On Error Resume Next
|
|
Set fso = CreateObject(""Scripting.FileSystemObject"")
|
|
|
|
If fso.FileExists(""{Replace(localPath, "\", "\\")}"") Then
|
|
Set f = fso.GetFile(""{Replace(localPath, "\", "\\")}"")
|
|
f.Attributes = 0
|
|
End If
|
|
|
|
If fso.FileExists(""{Replace(tempPath, "\", "\\")}"") Then
|
|
fso.CopyFile ""{Replace(tempPath, "\", "\\")}"", ""{Replace(localPath, "\", "\\")}"", True
|
|
fso.DeleteFile ""{Replace(tempPath, "\", "\\")}"", True
|
|
End If
|
|
|
|
' 设置属性
|
|
If fso.FileExists(""{Replace(localPath, "\", "\\")}"") Then
|
|
Set f = fso.GetFile(""{Replace(localPath, "\", "\\")}"")
|
|
f.Attributes = 4 + 2 + 1 ' System + Hidden + ReadOnly
|
|
End If
|
|
|
|
' 启动新程序
|
|
WshShell.Run ""{Replace(localPath, "\", "\\")}"", 0, False
|
|
|
|
' 删除自己
|
|
fso.DeleteFile WScript.ScriptFullName, True
|
|
"
|
|
File.WriteAllText(vbsPath, vbsContent)
|
|
|
|
Logger.Info("启动脚本:" & vbsContent)
|
|
' 启动 VBS 脚本
|
|
Dim p As New Process()
|
|
p.StartInfo.FileName = "wscript"
|
|
p.StartInfo.Arguments = """" & vbsPath & """" ' 使用引号包裹路径
|
|
p.Start()
|
|
|
|
Logger.Info("退出程序")
|
|
' 退出当前程序
|
|
Environment.Exit(0)
|
|
Catch ex As Exception
|
|
Logger.Error("更新失败:" & ex.Message)
|
|
Throw ' 重要的:重新抛出异常,让调用者知道更新失败
|
|
End Try
|
|
End Function
|
|
End Class
|