Download Progress

PrOpHeT

New member
Joined
Jan 22, 2006
Messages
1
Programming Experience
10+
I am using the folowing code to return data from a remote web server

[FONT=verdana,arial,helvetica]VB Code:[/FONT]
Dim Client As New System.Net.WebClient
Dim ByteArray() As Byte ByteArray = Client.DownloadData(Url)
Which works great, however I would like to display progress of data being retrieved for larger files.

does anyone know how I would do this or know another way to retrieve remote fies via http with progress status?


Thanks
 
Much good from that link. PrOpHeT, whether you want to display progress only of how much is downloaded so far, or also in context of how much there is to download to complete, you have to use the OpenRead method of WebClient. It returns a stream, so use a stream to read byte by byte to enable counting in between plus a stream to write, for instance FileStream. It is possible to get the file size prior to download in the ResponseHeaders Content-Length key. Code below does this:
VB.NET:
'add ProgressBar1 and Label1 to a project, then call this sub
 
Sub webclientprogress()
  Dim webpath As String = "http://www.ce.ntu.edu.tw/photo/bridge/bridge28bTension%20Bridge.jpg"
  Dim filename As String = Application.StartupPath & "\temp.jpg"
  Dim t As Date = Date.Now 'time the download
  Dim Client As New Net.WebClient
  Dim s As IO.Stream = Client.OpenRead(webpath)
  Dim fs As New IO.FileStream(filename, IO.FileMode.Create)
 
  'setup progress, get Content-Length in bytes from ResponseHeaders
  Dim totalbytes As Integer = CInt(Client.ResponseHeaders(Net.HttpResponseHeader.ContentLength))
  ProgressBar1.Value = 0
  ProgressBar1.Maximum = totalbytes
 
  'read and write the bytes 
  Dim b As Byte
  Try
    b = s.ReadByte
    Do While b <> -1
      fs.WriteByte(b)
      b = s.ReadByte
      'progress increase
      ProgressBar1.Value += 1
      If ProgressBar1.Value Mod 1000 = 0 Then 
        Label1.Text = ProgressBar1.Value & " bytes downloaded of " & totalbytes
        Application.DoEvents()
      End If
    Loop
  Catch ex As Exception
    'The end of the stream is reached.
  End Try
 
  'close streams
  s.Close()
  fs.Close()
 
  'progress end
  ProgressBar1.Value = 0
  Label1.Text = "downloaded " & totalbytes & " bytes in " _
    & Date.Now.Subtract(t).Seconds & " seconds"
 
  'display image in default application
  Process.Start(filename)
End Sub
 
Back
Top