2009-03 想写一个自动更新系统,就必须要用到下载这个功能。 先在这里练习一下。呵呵。
界面:
--
主要程序代码:
Private Sub BtnStartDownload_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles BtnStartDownload.Click iCount = Me.LstBoxFileList.Items.Count If iCount > 0 Then If Me.BtnStartDownload.Text.Equals("开始下载") Then Me.isCancelDownLoad = False Dim t As Thread = New Thread(New ThreadStart(AddressOf DownLoadFile)) t.IsBackground = True t.Name = "DownLoadFile" t.Start() Me.BtnStartDownload.Text = "取消下载任务" Else Me.isCancelDownLoad = True If myWebClient IsNot Nothing Then myWebClient.CancelAsync() evtPerDonwload.Set() End If ResetDownLoadPrg() Me.BtnStartDownload.Text = "开始下载" End If Else Me.BtnStartDownload.Text = "开始下载" ShowMsg("下载列表没有任务。") End If End Sub Private Sub DownLoadFile() Dim i As Integer = 0 Dim SaveFolder,FileFullPath,FileName,url As String evtPerDonwload = New ManualResetEvent(False) SaveFolder = Me.TxtBoxSaveFolder.Text For i = 0 To iCount - 1 If Me.isCancelDownLoad Then Exit For url = Me.LstBoxFileList.Items(i).ToString FileName = IO.Path.GetFileName(url) If SaveFolder = "" Then '如果是保存路径=空路径,就使用虚拟路径,下载到当前程序的文件夹里面。 FileFullPath = FileName Else '否则,保存到用户选择的文件夹里面。 FileFullPath = IO.Path.Combine(SaveFolder,FileName) End If Me.SmoothProgressBar1.Value = 0 myWebClient = New WebClient() AddHandler myWebClient.DownloadProgressChanged,AddressOf OnDownloadProgressChanged AddHandler myWebClient.DownloadFileCompleted,AddressOf OnDownloadFileCompleted evtPerDonwload.Reset() '文件保存在当前目录下. myWebClient.DownloadFileAsync(New Uri(url),FileName) '等待下载完成 evtPerDonwload.WaitOne() myWebClient.Dispose() myWebClient = Nothing Next '这里可以不用到这个,因为每次完成下载都会设置一次。加了反而会出现bug: 无法重设。 'ResetDownLoadPrg() 'If Me.isCancelDownLoad = False Then ResetDownLoadBtn() ' End If End Sub Private Sub OnDownloadProgressChanged(ByVal sender As Object,ByVal e As System.Net.DownloadProgressChangedEventArgs) '因为每一次下载一个文件时候都是New一个WebClient所以事件要动态添加到相对应的实例中。AddHandler ...OnDownloadProgressChanged '不可以用Handles myWebClient.DownloadProgressChanged此方法只可以用在 Dim WithEvents myWebClient 相当于静态的控件 ShowMsg(String.Format("正在下载:{0},下载:{1}/{2}",e.UserState.ToString,FileHelper.FormatFileSize(e.BytesReceived),FileHelper.FormatFileSize(e.TotalBytesToReceive))) Me.SmoothProgressBar1.Value = e.ProgressPercentage 'e.BytesReceived是接受文件的bytes 'e.TotalBytesToReceive是文件的总大小 'e.ProgressPercentage 是当前下载进度 End Sub Private Sub OnDownloadFileCompleted(ByVal sender As Object,ByVal e As System.ComponentModel.AsyncCompletedEventArgs) '因为每一次下载一个文件时候都是New一个WebClient所以事件要动态添加到相对应的实例中。AddHandler ...OnDownloadFileCompleted '不可以用Handles myWebClient.DownloadFileCompleted此方法只可以用在 Dim WithEvents myWebClient 相当于静态的控件 '发出释放同步进程信号 evtPerDonwload.Set() '重设下载进度信息和进度条 ResetDownLoadPrg() 'If Me.isCancelDownLoad = False Then ' If e.Error Is Nothing Then ' ShowMsg("下载完毕" & e.UserState.ToString()) ' Else ' ShowMsg("未完成下载: " & e.Error.Message) ' End If 'End If End Sub