locked
Visual Basic 2010 Downloading a file With Progress Bar RRS feed

  • Question

  • Is there any way in Visual Basic 2010 that I can download a file to a specific location, with a progress bar showing how much of the file has downloaded.

    Sunday, May 9, 2010 11:33 AM

Answers

  • Imports System.Net
    Public Class Form1
      
    Dim WithEvents WC As New WebClient
      
    Private Sub Button1_Click(ByVal sender As ObjectByVal e As EventArgs) Handles Button1.Click
        WC.DownloadFileAsync(
    New Uri("http://johnweinhold.com/Documents/DSVideoEditor.zip"), "DownloadedFile.zip")
      
    End Sub
      Private Sub WC_DownloadProgressChanged(ByVal sender As ObjectByVal e As DownloadProgressChangedEventArgs) Handles WC.DownloadProgressChanged
        ProgressBar1.Value = e.ProgressPercentage
      
    End Sub
    End
     Class

    • Marked as answer by jSherz Monday, May 10, 2010 6:35 AM
    Sunday, May 9, 2010 2:37 PM

All replies

  • Hi,

    yes it's possible. The question is in which way do you want download a file. Through http or ftp.

    You can get the filsize before the download start. The maximum value of progressbar would be the filesize in kb / mb or gb. To show the progress you can check every second how much mb are downloaded and add it as value to the value property.

     

    With this method you can show a download progress.

    Regards

    martinwy

    Sunday, May 9, 2010 11:41 AM
  • I would like to download the file through HTTP. Currently, I use the System.Net.WebClient method to download data (strings, small bits of info etc.). What method can I use that will download the file in a way that I can detect how much has been downloaded?
    Sunday, May 9, 2010 11:42 AM
  • here is an example from codeproject.  i haven't tried it yet

    Imports System.Net
    Public Class mainForm
    
      Dim whereToSave As String 'Where the program save the file
    
      Delegate Sub ChangeTextsSafe(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
      Delegate Sub DownloadCompleteSafe(ByVal cancelled As Boolean)
    
      Public Sub DownloadComplete(ByVal cancelled As Boolean)
        Me.txtFileName.Enabled = True
        Me.btnDownload.Enabled = True
        Me.btnCancel.Enabled = False
    
        If cancelled Then
    
          Me.Label4.Text = "Cancelled"
    
          MessageBox.Show("Download aborted", "Aborted", MessageBoxButtons.OK, MessageBoxIcon.Information)
    
    
        Else
          Me.Label4.Text = "Successfully downloaded"
    
          MessageBox.Show("Successfully downloaded!", "All OK", MessageBoxButtons.OK, MessageBoxIcon.Information)
    
    
        End If
    
        Me.ProgressBar1.Value = 0
        Me.Label5.Text = "Downloading: "
        Me.Label6.Text = "Save to: "
        Me.Label3.Text = "File size: "
        Me.Label2.Text = "Download speed: "
        Me.Label4.Text = ""
    
      End Sub
    
      Public Sub ChangeTexts(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
    
        Me.Label3.Text = "File Size: " & Math.Round((length / 1024), 2) & " KB"
    
        Me.Label5.Text = "Downloading: " & Me.txtFileName.Text
    
        Me.Label4.Text = "Downloaded " & Math.Round((position / 1024), 2) & " KB of " & Math.Round((length / 1024), 2) & "KB (" & Me.ProgressBar1.Value & "%)"
    
        If speed = -1 Then
          Me.Label2.Text = "Speed: calculating..."
        Else
          Me.Label2.Text = "Speed: " & Math.Round((speed / 1024), 2) & " KB/s"
        End If
    
        Me.ProgressBar1.Value = percent
    
    
      End Sub
    
      Private Sub btnDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDownload.Click
    
        If Me.txtFileName.Text <> "" AndAlso Me.txtFileName.Text.StartsWith("http://") Then
    
    
          Me.SaveFileDialog1.FileName = Me.txtFileName.Text.Split("/"c)(Me.txtFileName.Text.Split("/"c).Length - 1)
    
          If Me.SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    
            Me.whereToSave = Me.SaveFileDialog1.FileName
    
            Me.SaveFileDialog1.FileName = ""
    
            Me.Label6.Text = "Save to: " & Me.whereToSave
    
            Me.txtFileName.Enabled = False
            Me.btnDownload.Enabled = False
            Me.btnCancel.Enabled = True
    
            Me.BackgroundWorker1.RunWorkerAsync() 'Start download
    
          End If
    
        Else
    
          MessageBox.Show("Please insert valid URL for download", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    
        End If
    
      End Sub
    
      Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    
        'Creating the request and getting the response
        Dim theResponse As HttpWebResponse
        Dim theRequest As HttpWebRequest
        Try 'Checks if the file exist
    
          theRequest = WebRequest.Create(Me.txtFileName.Text)
          theResponse = theRequest.GetResponse
        Catch ex As Exception
    
          MessageBox.Show("An error occurred while downloading file. Possibe causes:" & ControlChars.CrLf & _
                  "1) File doesn't exist" & ControlChars.CrLf & _
                  "2) Remote server error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    
          Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
    
          Me.Invoke(cancelDelegate, True)
    
          Exit Sub
        End Try
        Dim length As Long = theResponse.ContentLength 'Size of the response (in bytes)
    
        Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
        Me.Invoke(safedelegate, length, 0, 0, 0) 'Invoke the TreadsafeDelegate
    
        Dim writeStream As New IO.FileStream(Me.whereToSave, IO.FileMode.Create)
    
        'Replacement for Stream.Position (webResponse stream doesn't support seek)
        Dim nRead As Integer
    
        'To calculate the download speed
        Dim speedtimer As New Stopwatch
        Dim currentspeed As Double = -1
        Dim readings As Integer = 0
    
        Do
    
          If BackgroundWorker1.CancellationPending Then 'If user abort download
            Exit Do
          End If
    
          speedtimer.Start()
    
          Dim readBytes(4095) As Byte
          Dim bytesread As Integer = theResponse.GetResponseStream.Read(readBytes, 0, 4096)
    
          nRead += bytesread
          Dim percent As Short = (nRead * 100) / length
    
          Me.Invoke(safedelegate, length, nRead, percent, currentspeed)
    
          If bytesread = 0 Then Exit Do
    
          writeStream.Write(readBytes, 0, bytesread)
    
          speedtimer.Stop()
    
          readings += 1
          If readings >= 5 Then 'For increase precision, the speed it's calculated only every five cicles
            currentspeed = 20480 / (speedtimer.ElapsedMilliseconds / 1000)
            speedtimer.Reset()
            readings = 0
          End If
        Loop
    
        'Close the streams
        theResponse.GetResponseStream.Close()
        writeStream.Close()
    
        If Me.BackgroundWorker1.CancellationPending Then
    
          IO.File.Delete(Me.whereToSave)
    
          Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
    
          Me.Invoke(cancelDelegate, True)
    
          Exit Sub
    
        End If
    
        Dim completeDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
    
        Me.Invoke(completeDelegate, False)
    
      End Sub
    
      Private Sub mainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Label4.Text = ""
      End Sub
    
      Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.BackgroundWorker1.CancelAsync() 'Send cancel request
      End Sub
    
      Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        MessageBox.Show("Created by Carmine_XX (www.thetotalsite.it)" & ControlChars.CrLf & "To report bugs/suggestions/comments please contact me by email: pikachu31@gmail.com or in the project page on CodeProject.com", "About", MessageBoxButtons.OK, MessageBoxIcon.Information)
      End Sub
    End Class
    

     


    FREE
    DEVELOPER TOOLS     CODE     PROJECTS

    DATABASE CODE GENERATOR
    DATABASE / GENERAL  APPLICATION TUTORIAL
    Upload Projects to share or get help on and post the generated links here in the forum
    www.srsoft.us
    Sunday, May 9, 2010 12:41 PM
  • Hi,

    okay.I have some code for you. With it you can get the headerinformation of a file. 

      Public Function getHttpHeaderfromFile(ByVal server As String, ByVal _
       filepath As String) As String
     
        Dim tcpClient As New Sockets.TcpClient
        Dim ipAddress As Net.IPAddress = Dns.GetHostEntry(server).AddressList(0)
     
        Dim ascii As Encoding = Encoding.ASCII
     
        Dim request As String = "HEAD " + filepath + " HTTP/1.1" + _
         ControlChars.Cr + ControlChars.Lf + _
                    "Host: " + server + ControlChars.Cr + _
                    ControlChars.Lf + _
                    "Accept: */*" + ControlChars.Cr + _
                    ControlChars.Lf + _
                    "Connection: close" + ControlChars.Cr + _
                    ControlChars.Lf + ControlChars.Cr + _
                    ControlChars.Lf
     
        Dim bytesSent As [Byte]() = ascii.GetBytes(request)
     
        tcpClient.Connect(ipAddress, 80)
     
        tcpClient.Client.Send(bytesSent, bytesSent.Length, 0)
     
        Dim bytes As Int32
        Dim bytesReceived(255) As [Byte]
        Dim receivedString As [String] = ""
     
        Do
          bytes = tcpClient.Client.Receive(bytesReceived, _
           bytesReceived.Length, 0)
          receivedString = receivedString + Encoding.ASCII.GetString( _
          bytesReceived, 0, bytes)
        Loop While bytes > 0
     
        Return receivedString.ToString
     
      End Function

    There you can check any information and look at the filesize.

    Regards

    martinwy

    Sunday, May 9, 2010 12:43 PM
  •   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles Button1.Click
    
        downloadFile("http://www.website.com/file.dat", "C:\downloads\file.dat")
    
      End Sub
    
      Private Sub downloadFile(ByVal srcPath As String, ByVal destPath As String)
    
        Dim wClient As New System.Net.WebClient()
        AddHandler wClient.DownloadProgressChanged, AddressOf downloadFile_ProgressChanged
    
        wClient.DownloadFileAsync(New System.Uri(srcPath), destPath)
    
      End Sub
    
      Private Sub downloadFile_ProgressChanged(ByVal sender As Object, ByVal e As System.Net.DownloadProgressChangedEventArgs)
        ProgressBar1.Maximum = e.TotalBytesToReceive
        ProgressBar1.Value = e.BytesReceived
        Application.DoEvents()
        If e.ProgressPercentage = 100 Then
          'download completed
        End If
      End Sub

    Thanks

    "Feel the Force !"  | My blog
    • Proposed as answer by Cor Ligthert Sunday, May 9, 2010 4:38 PM
    Sunday, May 9, 2010 1:59 PM
  • Imports System.Net
    Public Class Form1
      
    Dim WithEvents WC As New WebClient
      
    Private Sub Button1_Click(ByVal sender As ObjectByVal e As EventArgs) Handles Button1.Click
        WC.DownloadFileAsync(
    New Uri("http://johnweinhold.com/Documents/DSVideoEditor.zip"), "DownloadedFile.zip")
      
    End Sub
      Private Sub WC_DownloadProgressChanged(ByVal sender As ObjectByVal e As DownloadProgressChangedEventArgs) Handles WC.DownloadProgressChanged
        ProgressBar1.Value = e.ProgressPercentage
      
    End Sub
    End
     Class

    • Marked as answer by jSherz Monday, May 10, 2010 6:35 AM
    Sunday, May 9, 2010 2:37 PM
  • This gave me a Error that

    "An unhandled exception of type 'System.NullReferenceException' occurred in <project-name>.exe"

    Why is that


    0xeddie21847nc2012ol11i

    I'm using VS2012

    • Edited by 0xEddie Sunday, February 2, 2014 10:36 AM
    Sunday, February 2, 2014 10:35 AM
  • Really thx sir , it worked 100% fine :)
    Monday, September 7, 2015 12:41 PM
  • Try this

    Imports System.Net

    Private Sub cmdsave_Click(sender As Object, e As EventArgs) Handles cmdsave.Click        SaveFileDialog1.Filter=".jpg|*.jpg|.exe|*.exe|.zip|*.zip|.rar|*.rar|.png|*.png|.gif|*.gif|.mp4|*.mp4|.iso|*.iso|.mp3|*.mp3|.dotx|*.dotx"
            SaveFileDialog1.ShowDialog()
            TextBox2.Text = SaveFileDialog1.FileName
        End Sub
        Public WithEvents download As WebClient
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            download = New WebClient
            download.DownloadFileAsync(New Uri(TextBox1.Text), TextBox2.Text)
        End Sub

        Private Sub download_downloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles download.DownloadProgressChanged
            ProgressBar1.Value = e.ProgressPercentage

        End Sub                    'Hope This helps

    Thursday, September 26, 2019 7:34 AM