VB winform自动更新 笔记

时间:2021-09-22 18:01:05

看网上各种自动更新方法,最后自己找了个比较简单的,在此做个笔记。

服务器上的共享盘里存放生成的可执行文件和XML格式的配置:

<?xml version="1.0" encoding="utf-8"?>

<AutoUpdate>
<version>PackingBarcodeValidation2.0</version>
<downloadURL>//ip/PackingBarcodeValidation2.0.exe</downloadURL>
</AutoUpdate>

直接上代码:

'update revision
Dim updateXMLURL As String = "//ip/revision.xml"
Dim version As String = Nothing
Dim downloadURL As String = Nothing

If System.IO.File.Exists(updateXMLURL) Then

Dim xmldoc As New XmlDocument()
xmldoc.Load(updateXMLURL)

'获取节点列表
Dim topM As XmlNodeList = xmldoc.SelectNodes("//AutoUpdate")
For Each element As XmlElement In topM
version = element.GetElementsByTagName("version")(0).InnerText
downloadURL = element.GetElementsByTagName("downloadURL")(0).InnerText
Next
If version <> Me.Text And System.IO.File.Exists(downloadURL) Then

Me.DownloadFile(downloadURL, "./" & version & ".exe", Me.ProgressBar1)

MsgBox("系统升级成功,请使用新的系统" & version & ".exe")
Me.Close()

End If

End If

下载方法代码:

''' <summary>
''' c#,.net 下载文件
''' </summary>
''' <param name="URL">下载文件地址</param>
'''
''' <param name="Filename">下载后的存放地址</param>
''' <param name="Prog">用于显示的进度条</param>
'''
Public Sub DownloadFile(ByVal URL As String, ByVal filename As String, ByVal prog As System.Windows.Forms.ProgressBar)
Dim percent As Single = 0
Try
URL = "http:" & URL
Dim Myrq As System.Net.HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(URL), System.Net.HttpWebRequest)
Dim myrp As System.Net.HttpWebResponse = DirectCast(Myrq.GetResponse(), System.Net.HttpWebResponse)
Dim totalBytes As Long = myrp.ContentLength
If prog IsNot Nothing Then
prog.Maximum = CInt(totalBytes)
End If
Dim st As System.IO.Stream = myrp.GetResponseStream()
Dim so As System.IO.Stream = New System.IO.FileStream(filename, System.IO.FileMode.Create)
Dim totalDownloadedByte As Long = 0
Dim by As Byte() = New Byte(1023) {}
Dim osize As Integer = st.Read(by, 0, CInt(by.Length))
While osize > 0
totalDownloadedByte = osize + totalDownloadedByte
System.Windows.Forms.Application.DoEvents()
so.Write(by, 0, osize)
If prog IsNot Nothing Then
prog.Value = CInt(totalDownloadedByte)
End If
osize = st.Read(by, 0, CInt(by.Length))

percent = CSng(totalDownloadedByte) / CSng(totalBytes) * 100
'label1.Text = "当前补丁下载进度" & percent.ToString() & "%"
'必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
System.Windows.Forms.Application.DoEvents()
End While
so.Close()
st.Close()
Catch generatedExceptionName As System.Exception
Throw
End Try
End Sub

在界面上添加了一个进度条。