0

I am creating a file downloader using backgroundworker & i want to save the progress of backgroundworker so that when i restart the application, on resume, it start the download where i closed last time.

Any help ? Here is My code for Downloader

Public Class cls_FileDownloader
Dim FileSave As String
Delegate Sub DownloadFIlesafe(ByVal Cancelled As Boolean)
Delegate Sub ChangeTextsSafe(ByVal length As Long, ByVal position As Double, ByVal percent As Long, ByVal speed As Long)
Private Sub cls_FileDownloader_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Label1.Text = ""
    btn_Cancel.Enabled = False

End Sub

Private Sub btn_Download_Click(sender As Object, e As EventArgs) Handles btn_Download.Click
    If Me.txt_Url.Text <> "" Then
        Me.SaveFile.FileName = txt_Url.Text.Split("\"c)(txt_Url.Text.Split("\"c).Length - 1)
        If SaveFile.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            FileSave = SaveFile.FileName
            SaveFile.FileName = ""
            lbl_SaveTO.Text = "Save To:" & FileSave

            txt_Url.Enabled = False
            btn_Download.Enabled = False
            btn_Cancel.Enabled = True

            bg_Worker.RunWorkerAsync()
        End If
    Else
        MessageBox.Show("Please Insert valid file path", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)

    End If

End Sub

Private Sub bg_Worker_DoWork(sender As Object, e As DoWorkEventArgs) Handles bg_Worker.DoWork

    Dim response As FileWebResponse
    Dim request As FileWebRequest
    Try
        request = WebRequest.Create(txt_Url.Text)
        response = request.GetResponse

    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Dim cancelDelegate As New DownloadFIlesafe(AddressOf Download_Complete)
        Me.Invoke(cancelDelegate, True)
        Exit Sub
    End Try

    Dim length As Long = response.ContentLength
    Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
    Me.Invoke(safedelegate, length, 0, 0, 0)
    Dim writeStream As New IO.FileStream(Me.FileSave, IO.FileMode.Create)


    Dim nRead As Double

    'To calculate the download speed
    Dim speedtimer As New Stopwatch
    Dim currentspeed As Long = -1
    Dim readings As Integer = 0

    Do

        If bg_Worker.CancellationPending Then 'If user abort download
            Exit Do
        End If

        speedtimer.Start()

        Dim readBytes(4095) As Byte
        Dim bytesread As Long = response.GetResponseStream.Read(readBytes, 0, 4096)

        nRead += bytesread
        Dim percent As Long = (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
    response.GetResponseStream.Close()
    writeStream.Close()
    If Me.bg_Worker.CancellationPending Then

        IO.File.Delete(Me.FileSave)

        Dim cancelDelegate As New DownloadFIlesafe(AddressOf Download_Complete)

        Me.Invoke(cancelDelegate, True)

        Exit Sub

    End If

    Dim completeDelegate As New DownloadFIlesafe(AddressOf Download_Complete)

    Me.Invoke(completeDelegate, False)


End Sub
Afaq
  • 3
  • 4
  • 1
    A `BackgroundWorker` doesn't have any progress. It just sits there. It raises it's `DoWork` event and then you can perform some task in the event handler. It's that task that has some level of progress but the `BackgroundWorker` knows nothing about it. It's up to you to determine how to measure that progress and to then do so. – jmcilhinney Sep 21 '16 at 12:13
  • Then how can i get the previous state of my downloading file on restart. @jmcilhinney – Afaq Sep 21 '16 at 16:18
  • Please provide some code to help us understand more. As @jmcilhinney pointed out 'BackgroundWorker' does not have any progress. So the code in the event handler would be helpful in order to help you. You may want to rewrite your question? – Malcor Sep 21 '16 at 16:38
  • @Malcor I've added the code for file downloader. – Afaq Sep 21 '16 at 16:53
  • @Afaq You can use My.Settings to store the current progress. [HttpWebRequest or WebRequest - Resume Download ASP.NET](http://stackoverflow.com/a/1336343/1115360) gives information on how to get the server to send from a specified point in the file - if it has that capability. – Andrew Morton Sep 21 '16 at 17:37
  • To get the filename from the URL *reliably*, you can use `SaveFile.FileName = IO.Path.GetFileName(New Uri(s).AbsolutePath)` - it will remove any querystring if present, e.g. `"http://www.example.com/x/y/xqr.jpg?x=1&y=2"` will yield "xqr.jpg". – Andrew Morton Sep 21 '16 at 18:00
  • @AndrewMorton Thanks. I've got some clue from your provided link. – Afaq Sep 22 '16 at 04:34

0 Answers0