Results 1 to 10 of 10

Thread: download a file

  1. #1

    Thread Starter
    Frenzied Member usamaalam's Avatar
    Join Date
    Nov 2002
    Location
    Karachi
    Posts
    1,308

    download a file

    Hello,

    How can I download a file from HTTP in VB.NET with progressbar ??

    Thanks.

  2. #2
    Sleep mode
    Join Date
    Aug 2002
    Location
    RUH
    Posts
    8,083
    For the client download , use the code below . You need to figure out how to calculate progress of the progressbar . (maybe based on the size of the file divided by speed or remaining file size . I dont' know ) . One important thing you have to keep in mind . If you are planning to do multiple instant downloads then go with threadings .
    VB Code:
    1. Private Sub DownLoadFile()
    2.         Dim wClient As New WebClient
    3.         Dim adres As String = "http://www.whatever.com/anyfile.xxx"
    4.         wClient.DownloadFile(adres, "c:\anyfile.xxx")
    5.     End Sub

  3. #3
    Hyperactive Member stingrae's Avatar
    Join Date
    Apr 2002
    Location
    Sydney
    Posts
    401
    i was given this code from a forum member a few months ago. it works really well.

    Code:
    Option Explicit On 
    Option Strict On
    
    Imports System
    Imports System.Net
    Imports System.Text
    
    Public Class DownloadWorker
        Private _size As Long
        Private mRead As Long
        Private _status As DownLoadStatus
        Private _errorDescription As String
        Private _sourceURL As String
        Private _destPath As String
        Private _referer As String
        Public Sub New()
            MyBase.new()
            _status = DownLoadStatus.Idle
        End Sub
        Public Sub New(ByVal sSourceURL As String, ByVal sDestPath As String)
            MyBase.new()
            _sourceURL = sSourceURL
            _destPath = sDestPath
        End Sub
        Public Sub New(ByVal sSourceURL As String, ByVal sDestPath As String, ByVal sReferer As String)
            MyBase.new()
            _sourceURL = sSourceURL
            _destPath = sDestPath
            _referer = sReferer
        End Sub
    
        Public Enum DownLoadStatus
            Idle = 0
            Connecting = 1
            Connected = 2
            Downloading = 3
            Completed = 4
            ErrorOccured = 5
        End Enum
    
        Public Event StatusChanged(ByRef sender As DownloadWorker, ByVal OldStatus As DownLoadStatus, ByVal NewStatus As DownLoadStatus)
        Public Event ProgressChanged(ByRef sender As DownloadWorker)
        Public Property SourceURL() As String
            Get
                Return _sourceURL
            End Get
            Set(ByVal Value As String)
                Select Case _status
                    Case DownLoadStatus.Connected, DownLoadStatus.Connecting, DownLoadStatus.Downloading
                        Throw New InvalidOperationException("SourceURL cannot be changed while download is in progress")
                    Case Else
                        _sourceURL = Value
                End Select
            End Set
        End Property
        Public Property DestPath() As String
            Get
                Return _destPath
            End Get
            Set(ByVal Value As String)
                Select Case _status
                    Case DownLoadStatus.Connected, DownLoadStatus.Connecting, DownLoadStatus.Downloading
                        Throw New InvalidOperationException("Destination Path cannot be changed while download is in progress")
                    Case Else
                        _destPath = Value
                End Select
            End Set
        End Property
        Public Property Referer() As String
            Get
                Return _referer
            End Get
            Set(ByVal Value As String)
                Select Case _status
                    Case DownLoadStatus.Connected, DownLoadStatus.Connecting, DownLoadStatus.Downloading
                        Throw New InvalidOperationException("Referer cannot be changed while download is in progress")
                    Case Else
                        _referer = Value
                End Select
            End Set
        End Property
    
        Public ReadOnly Property Status() As DownLoadStatus
            Get
                Return _status
            End Get
        End Property
        Public ReadOnly Property Progress() As Double
            Get
                If _size = 0 Then
                    Return 0
                Else
                    Return mRead / _size
                End If
            End Get
        End Property
        Public ReadOnly Property Size() As Long
            Get
                Return _size
            End Get
        End Property
        Public ReadOnly Property Downloaded() As Long
            Get
                Return mRead
            End Get
        End Property
        Public ReadOnly Property ErrorDescription() As String
            Get
                Return _errorDescription
            End Get
        End Property
        Private Sub ChangeStatus(ByVal NewStatus As DownLoadStatus)
            Dim Temp As DownLoadStatus
            Temp = _status
            _status = NewStatus
            RaiseEvent StatusChanged(Me, Temp, NewStatus)
        End Sub
        Public Sub DownloadFile()
            Dim bBuffer() As Byte
            Const BlockSize As Integer = 4096
            Dim iRead As Integer
            Dim iReadTotal As Integer
            Dim iTotalSize As Integer
            If _sourceURL = "" Then
                Throw New InvalidOperationException("No Source URL specified")
                Exit Sub
            End If
            If _destPath = "" Then
                Throw New InvalidOperationException("No Destination Path specified")
                Exit Sub
            End If
    
            Try
                Call ChangeStatus(DownLoadStatus.Connecting)
                Dim wr As HttpWebRequest = CType(WebRequest.Create(_sourceURL), HttpWebRequest)
                If _referer <> "" Then
                    wr.Referer = _referer
                End If
                Dim resp As HttpWebResponse = CType(wr.GetResponse(), HttpWebResponse)
                _size = resp.ContentLength
                Call ChangeStatus(DownLoadStatus.Connected)
                Dim sIn As IO.Stream = resp.GetResponseStream
                Dim sOut As New IO.FileStream(_destPath, IO.FileMode.Create)
                ReDim bBuffer(BlockSize - 1)
                Call ChangeStatus(DownLoadStatus.Downloading)
                iRead = sIn.Read(bBuffer, 0, BlockSize)
                mRead = iRead
                While iRead > 0
                    RaiseEvent ProgressChanged(Me)
                    sOut.Write(bBuffer, 0, iRead)
                    iRead = sIn.Read(bBuffer, 0, BlockSize)
                    mRead += iRead
                End While
                sIn.Close()
                sOut.Close()
                Call ChangeStatus(DownLoadStatus.Completed)
            Catch ex As Exception
                _errorDescription = ex.Message
                Call ChangeStatus(DownLoadStatus.ErrorOccured)
            End Try
        End Sub
    
    End Class
    
        Private Sub btnDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDownload.Click
            ' Save page to folder
            Dim strURL As String
            strThisFile = Environment.GetEnvironmentVariable("TEMP") & "\ThisPage.htm"
            strURL = txtURL.Text
            dlw = New DownloadWorker(strURL, strThisFile)
            Dim t As New Threading.Thread(AddressOf dlw.DownloadFile)
            t.Start()
        End Sub
    
        Private Sub dlw_ProgressChanged(ByRef sender As DownloadWorker) Handles dlw.ProgressChanged
            StatusBar1.Panels(0).Text = Format(sender.Progress, "     " & "0 %")
        End Sub
    
        Private Sub dlw_StatusChanged(ByRef sender As DownloadWorker, ByVal OldStatus As DownloadWorker.DownLoadStatus, ByVal NewStatus As DownloadWorker.DownLoadStatus) Handles dlw.StatusChanged
            Select Case NewStatus
                Case DownloadWorker.DownLoadStatus.Completed
                    StatusBar1.Panels(0).Text = "Completed"
                Case DownloadWorker.DownLoadStatus.Connected
                    StatusBar1.Panels(0).Text = "Connected"
                Case DownloadWorker.DownLoadStatus.Connecting
                    StatusBar1.Panels(0).Text = "Connecting"
                Case DownloadWorker.DownLoadStatus.Downloading
                    StatusBar1.Panels(0).Text = "Downloading"
                Case DownloadWorker.DownLoadStatus.ErrorOccured
                    StatusBar1.Panels(0).Text = sender.ErrorDescription
                Case DownloadWorker.DownLoadStatus.Idle
                    StatusBar1.Panels(0).Text = "Idle"
            End Select
        End Sub
    "The passion lives to keep your faith, though all are different, all are great" ... Michael Hutchence 1960-1997.

    Windows & Web Developer
    Specialising in Visual Basic .Net & Client Server Programming & Client/Customer Relations Databases
    Sutherland Shire, Sydney Australia
    www.stingrae.com.au
    Developer of Arnold - Gym & Martial Arts Database Management System
    www.gymdatabase.com.au

  4. #4
    Addicted Member
    Join Date
    Apr 2003
    Location
    Australia
    Posts
    252

    Smile

    Hi,

    I tried both of these codes today and the file downloaded properly the local disk.

    Pirate:
    VB Code:
    1. Dim wClient As New WebClient
    2.         Dim adres As String = "http://mcored.2minnoodle.net/downloads/bin/test.txt"
    3.         wClient.DownloadFile(adres, Application.StartupPath + "\test.txt")
    4.         MessageBox.Show("test.txt downloaded successfully")
    MSDN:
    VB Code:
    1. Dim remoteUri As String = "http://mcored.2minnoodle.net/downloads/bin/"
    2.         Dim fileName As String = "test.txt"
    3.         Dim myStringWebResource As String = Nothing
    4.         Dim myWebClient As New WebClient
    5.         myStringWebResource = remoteUri + fileName
    6.         myWebClient.DownloadFile(myStringWebResource, fileName)
    7.         MessageBox.Show(fileName + " downloaded successfully")

    However there is something strange happening.

    The data in the downloaded textfile does not look the same as the date in the original textfile.":


    The original file looks like this:


    I would be grateful if anybody could help me by explaining what causes this problem and how to rectify it.

    Much appreciated,
    McoreD

  5. #5
    Frenzied Member
    Join Date
    Jun 2001
    Location
    USA
    Posts
    1,026
    You're prolly downloading a file off of a linux based server...

    These systems don't look at the return/endline characters the same as in Windows... Try opening the file in Wordpad and see what happens...


    squirrelly1
    Now happily married and still crankin' away at the keyboard. Life is grand for a coder, no?

  6. #6
    Lively Member sameer spitfire's Avatar
    Join Date
    Nov 2001
    Location
    India
    Posts
    120
    which reference u have added for WebClient
    with Regards
    sameer Mulgaonkar

  7. #7
    Frenzied Member Asgorath's Avatar
    Join Date
    Sep 2004
    Location
    Saturn
    Posts
    2,036
    Originally posted by sameer spitfire
    which reference u have added for WebClient
    Hi, not a reference its an import statement

    VB Code:
    1. imports system.net

    Regards
    Jorge
    "The dark side clouds everything. Impossible to see the future is."

  8. #8
    Lively Member
    Join Date
    Oct 2004
    Posts
    123
    Sorry to addon, this coding is very interesting.. How you guys defined Web Client as?

    How can I code a progress bar to go straight to 99 percent and a while to 100%?. I know that coding a progress bar can't be accurate. Any easy tutorial on coding progress bar?
    The Power Of Sharing Knowledge!

  9. #9
    Lively Member sameer spitfire's Avatar
    Join Date
    Nov 2001
    Location
    India
    Posts
    120
    dim WC as new system.net.webclient
    with Regards
    sameer Mulgaonkar

  10. #10
    Lively Member
    Join Date
    Oct 2004
    Posts
    123
    Thanks.. Waiting for the progress bar information..
    The Power Of Sharing Knowledge!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width