Click here to Skip to main content
15,888,313 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello All,

we (a couple of friend and myself) are currently working on a web browser with a webkit based webengine (like chrome or safari).
but we came across a problem.
the file downloader isn't working correctly, so we made a own download manager.
but that one doesn't work either.
we found the problem. it has to do with the way the browser is downloading the file
for example if we try to download a project from codeproject it downloads normaly but when we try to open th .zip file we downloaded it gives us an error (damaged archive file)
but thats not al if we rename the file frome projectname.zip to projectname.php
it opens properly and it shows the download page of codeproject.
so for an unknow reason the filedownloader is downloading the pgae with the name + extension of the file we actually want

but it only occurs when we download a file from an url (for example http://www.codeproject.com/KB/IP/MyDownloader/MyDownloader_src.zip[^] (which is actualy a page))

but when we download a file like http://dl.bukkit.org/latest-rb/craftbukkit.jar[^] it works fine and it downloads thecraftbukkit.jar and not "the page"

please help us because it is realy driving us mad


PS. we are using the folowing code
(full downloader.vb file and the part inside main_win)

Main_win
VB
Public Sub WebKitBrowser1_DownloadBegin(Sender As Object, e As WebKit.FileDownloadBeginEventArgs)
        Dim time As DateTime = DateTime.Now
        Dim format As String = "d/M/yyyy HH:mm"
        Dim newItem As New ListViewItem(e.SuggestedFileName)
        Downloader.txtUrl.Text = e.Url.ToString
        Downloader.txtPath.Text = GetDownloadsPath() + "\" + e.SuggestedFileName
        Downloader.Show()
        newItem.SubItems.Add(e.Url.ToString)
        newItem.SubItems.Add(time.ToString(format))
        ListView1.Items.Add(newItem)
        My.Settings.Downloads.Add(e.SuggestedFileName + "|" + e.Url.ToString + "|" + time.ToString(format))
        My.Settings.Save()
    End Sub


downloader.vb
VB
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Net
Imports System.IO
Imports System.Threading

Public Class Downloader
    ' The thread inside which the download happens
    Private thrDownload As Thread
    ' The stream of data retrieved from the web server
    Private strResponse As Stream
    ' The stream of data that we write to the harddrive
    Private strLocal As Stream
    ' The request to the web server for file information
    Private webRequest As HttpWebRequest
    ' The response from the web server containing information about the file
    Private webResponse As HttpWebResponse
    ' The progress of the download in percentage
    Private Shared PercentProgress As Integer
    ' The delegate which we will call from the thread to update the form
    Private Delegate Sub UpdateProgessCallback(BytesRead As Int64, TotalBytes As Int64)
    ' When to pause
    Private goPause As Boolean = False

    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub btnDownload_Click(sender As Object, e As EventArgs)
        If thrDownload IsNot Nothing AndAlso thrDownload.ThreadState = ThreadState.Running Then
            MessageBox.Show(Main_Win.rm.GetString("Downloader_Message1"), Main_Win.rm.GetString("Downloader_Message1Title"), MessageBoxButtons.OK, MessageBoxIcon.[Error])
        Else
            ' Let the user know we are connecting to the server
            lblProgress.Text = Main_Win.rm.GetString("Downloader_lblProgressStarting")
            ' Create a new thread that calls the Download() method
            thrDownload = New Thread(New ParameterizedThreadStart(AddressOf Download))
            ' Start the thread, and thus call Download(); start downloading from the beginning (0)
            thrDownload.Start(0)
            ' Enable the Pause/Resume button
            btnPauseResume.Enabled = True
            ' Set the button's caption to Pause because a download is in progress
            btnPauseResume.Text = Main_Win.rm.GetString("Downloader_btnPause")
        End If
    End Sub

    Private Sub UpdateProgress(BytesRead As Int64, TotalBytes As Int64)
        ' Calculate the download progress in percentages
        PercentProgress = Convert.ToInt32((BytesRead * 100) \ TotalBytes)
        ' Make progress on the progress bar
        prgDownload.Value = PercentProgress
        ' Display the current progress on the form
        lblProgress.Text = Main_Win.rm.GetString("Downloader_lblProgressDownloaded") + ":" + BytesRead + Main_Win.rm.GetString("Downloader_lblProgressOutOf") + TotalBytes + " (" & PercentProgress + "%)"
    End Sub

    Private Sub Download(startPoint As Object)
        Try
            ' Put the object argument into an int variable
            Dim startPointInt As Integer = Convert.ToInt32(startPoint)
            ' Create a request to the file we are downloading
            webRequest = DirectCast(Net.WebRequest.Create(txtUrl.Text), HttpWebRequest)
            ' Set the starting point of the request
            webRequest.AddRange(startPointInt)

            ' Set default authentication for retrieving the file
            webRequest.Credentials = CredentialCache.DefaultCredentials
            ' Retrieve the response from the server
            webResponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)
            ' Ask the server for the file size and store it
            Dim fileSize As Int64 = webResponse.ContentLength

            ' Open the URL for download 
            strResponse = webResponse.GetResponseStream()

            ' Create a new file stream where we will be saving the data (local drive)
            If startPointInt = 0 Then
                strLocal = New FileStream(txtPath.Text, FileMode.Create, FileAccess.Write, FileShare.None)
            Else
                strLocal = New FileStream(txtPath.Text, FileMode.Append, FileAccess.Write, FileShare.None)
            End If

            ' It will store the current number of bytes we retrieved from the server
            Dim bytesSize As Integer = 0
            ' A buffer for storing and writing the data retrieved from the server
            Dim downBuffer As Byte() = New Byte(2047) {}

            ' Loop through the buffer until the buffer is empty
            While (InlineAssignHelper(bytesSize, strResponse.Read(downBuffer, 0, downBuffer.Length))) > 0
                ' Write the data from the buffer to the local hard drive
                strLocal.Write(downBuffer, 0, bytesSize)
                ' Invoke the method that updates the form's label and progress bar
                Me.Invoke(New UpdateProgessCallback(AddressOf Me.UpdateProgress), New Object() {strLocal.Length, fileSize + startPointInt})

                If goPause = True Then
                    Exit While
                End If
            End While
        Finally
            ' When the above code has ended, close the streams
            strResponse.Close()
            strLocal.Close()
        End Try
    End Sub

    Private Sub btnStop_Click(sender As Object, e As EventArgs)
        ' Abort the thread that's downloading
        thrDownload.Abort()
        ' Close the web response and the streams
        webResponse.Close()
        strResponse.Close()
        strLocal.Close()
        ' Set the progress bar back to 0 and the label
        prgDownload.Value = 0
        lblProgress.Text = Main_Win.rm.GetString("Downloader_lblProgressStopped")
        ' Disable the Pause/Resume button because the download has ended
        btnPauseResume.Enabled = False
    End Sub

    Private Sub btnPauseResume_Click(sender As Object, e As EventArgs)
        ' If the thread exists
        If thrDownload IsNot Nothing Then
            If btnPauseResume.Text = Main_Win.rm.GetString("Downloader_btnPause") Then
                ' The Pause/Resume button was set to Pause, thus pause the download
                goPause = True

                ' Now that the download was paused, turn the button into a resume button
                btnPauseResume.Text = Main_Win.rm.GetString("Downloader_btnResume")

                ' Close the web response and the streams
                webResponse.Close()
                strResponse.Close()
                strLocal.Close()
                ' Abort the thread that's downloading
                thrDownload.Abort()
            Else
                ' The Pause/Resume button was set to Resume, thus resume the download
                goPause = False

                ' Now that the download was resumed, turn the button into a pause button
                btnPauseResume.Text = Main_Win.rm.GetString("Downloader_btnPause")

                Dim startPoint As Long = 0

                If File.Exists(txtPath.Text) Then
                    startPoint = New FileInfo(txtPath.Text).Length
                Else
                    MessageBox.Show(Main_Win.rm.GetString("Downloader_Message2"), Main_Win.rm.GetString("Downloader_Message2Title"), MessageBoxButtons.OK, MessageBoxIcon.[Error])
                End If

                ' Let the user know we are connecting to the server
                lblProgress.Text = Main_Win.rm.GetString("Downloader_lblProgressResume")
                ' Create a new thread that calls the Download() method
                thrDownload = New Thread(New ParameterizedThreadStart(AddressOf Download))
                ' Start the thread, and thus call Download()
                thrDownload.Start(startPoint)
                ' Enable the Pause/Resume button
                btnPauseResume.Enabled = True
            End If
        Else
            MessageBox.Show(Main_Win.rm.GetString("Downloader_Message3"), Main_Win.rm.GetString("Downloader_Message3Title"), MessageBoxButtons.OK, MessageBoxIcon.[Error])
        End If
    End Sub
    Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
        target = value
        Return value
    End Function
    Private Sub Downloader_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.lblUrl.Text = Main_Win.rm.GetString("Downloader_lblUrl")
        Me.lblPath.Text = Main_Win.rm.GetString("Downloader_lblPath")
        Me.lblProgress.Text = Main_Win.rm.GetString("Downloader_lblProgressWait")
        Me.btnDownload.Text = Main_Win.rm.GetString("Downloader_btnDownload")
        Me.btnStop.Text = Main_Win.rm.GetString("Downloader_btnStop")
        Me.btnPauseResume.Text = Main_Win.rm.GetString("Downloader_btnPause")

        Me.lblUrl.ForeColor = Color.Black
        Me.lblPath.ForeColor = Color.Black
        Me.lblProgress.ForeColor = Color.Black

        Me.lblUrl.BackColor = Color.Transparent
        Me.lblPath.BackColor = Color.Transparent
        Me.lblProgress.BackColor = Color.Transparent

        Me.btnDownload.ForeColor = Color.Black
        Me.btnStop.ForeColor = Color.Black
        Me.btnPauseResume.ForeColor = Color.Black

        Me.btnDownload.BackColor = Color.Transparent
        Me.btnStop.BackColor = Color.Transparent
        Me.btnPauseResume.BackColor = Color.Transparent
    End Sub
End Class
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900