Rubrik: HTML/Internet/Netzwerk · Internet / Browser / IE | VB-Versionen: VB2005, VB2008 | 20.11.08 |
HTTP-Download mit Fortschrittsanzeige Hier wird gezeigt, wie sich eine Datei aus dem Internet asnychros downloaden lässt inkl. einer Fortschrittsanzeige. | ||
Autor: Dieter Otter | Bewertung: | Views: 16.255 |
www.tools4vb.de | System: Win2k, WinXP, Win7, Win8, Win10, Win11 | Beispielprojekt auf CD |
Mit Hilfe der System.Net.WebClient Klasse lässt sich eine Datei aus dem Internet sehr einfach asynchros downloaden und dabei auch noch der aktuelle Fortschritt anzeigen.
Erstellen Sie ein neues Windows-Forms Projekt, platzieren auf die Form ein ProgressBar-Control (ProgressBar1), sowie ein Label (lblProgress) und einen Button (Button1).
Imports System.Net
Public Class Form1 ' WebClient für Datei-Download Private WithEvents httpClient As WebClient
' Datei-Download starten Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ' Fortschrittsanzeige zurücksetzen lblProgress.Text = "0 KB" ProgressBar1.Value = 0 ProgressBar1.Maximum = 100 ' Neue Instanz der WebClient-Klasse erstellen httpClient = New WebClient ' URL der Datei (hier die vollständige URL eintragen) Dim sURL As String = "http://www..." ' Ziel-Datei (lokal) Dim sLocalFile As String = "d:\temp\myFile.exe" Button1.Enabled = False Try ' Download asynchros starten, damit wir den Fortschritt ' anzeigen können httpClient.DownloadFileAsync(New Uri(sURL), sLocalFile) lblProgress.Visible = True ProgressBar1.Visible = True Catch ex As Exception MsgBox("Fehler!" & vbCrLf & ex.Message, MsgBoxStyle.Exclamation) Button1.Enabled = True End Try End Sub
' Download beendet Private Sub httpClient_DownloadFileCompleted(ByVal sender As Object, _ ByVal e As System.ComponentModel.AsyncCompletedEventArgs) _ Handles httpClient.DownloadFileCompleted MsgBox("Download erfolgreich durchgeführt", MsgBoxStyle.Information) ProgressBar1.Visible = False lblProgress.Visible = False Button1.Enabled = True End Sub
' Fortschrittsanzeige Private Sub httpClient_DownloadProgressChanged(ByVal sender As Object, _ ByVal e As System.Net.DownloadProgressChangedEventArgs) _ Handles httpClient.DownloadProgressChanged With ProgressBar1 ' prozentuale Anzeige des Fortschritts in der ProgressBar .Value = e.ProgressPercentage ' KB-Fortschrittanzeige im Label Dim TotalBytes As Long = e.TotalBytesToReceive / 1024 Dim Bytes As Long = e.BytesReceived / 1024 If TotalBytes < 1 Then TotalBytes = 1 If Bytes < 1 Then Bytes = 1 lblProgress.Text = Bytes.ToString & " KB von " & TotalBytes.ToString & " KB" End With End Sub
End Class