Solved

use request http to download files, it only limit for 3 files. Please help to bypass the problem

Posted on 2007-11-16
5
275 Views
Last Modified: 2013-11-07
 
Hi
I write a windows base client side system to download files from internet.
But unfortuanlly that http request only  support for 3 files download. How can I solve this ? I need to do batch donwnload from internet


Delegate Sub ChangeTextsSafe(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal totalpercent As Integer, ByVal speed As Double)
   

 Public Sub ChangeTexts(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal totalpercent As Integer, ByVal speed As Double)

        Me.lblFileSize.Text = "File Size: " & Math.Round((length / 1024), 2) & " KB"

        Me.lblFileName.Text = "Downloading: " & filename

        Me.lblStatus.Text = "Downloaded " & Math.Round((position / 1024), 2) & " KB of " & Math.Round((length / 1024), 2) & "KB (" & Me.ProgressBar.Value & "%)"

        If speed = -1 Then
            Me.lblSpeed.Text = "Speed: calculating..."
        Else
            Me.lblSpeed.Text = "Speed: " & Math.Round((speed / 1024), 2) & " KB/s"
        End If

        Me.ProgressBar.Value = percent
        Me.ProgressBarMain.Value = totalpercent

    End Sub

    Private Sub backgroundwork()
        Dim ServerPath As String
        Dim strTargetPath As String
        Dim strTargetPathFile As String
        Dim strDestinationPath As String
        Dim strDestinationPathFile As String
        strDestinationPath = Application.StartupPath & "\flash"
        ServerPath = "http://cckoay/file_manager_web/flash/merchant/"
        strTargetPath = ServerPath & strMerchant


        Dim countUpdatedFiles As Integer
        Dim j As Integer
        countUpdatedFiles = ds.Tables(0).Rows.Count

        If countUpdatedFiles >= 0 Then
            '  
            For j = 0 To countUpdatedFiles - 1
                filename = strTargetPath & "/" & ds.Tables(0).Rows(j)(0)
                Dim theResponse As HttpWebResponse
                Dim theRequest As HttpWebRequest
                Try 'Checks if the file exist

                    theRequest = WebRequest.Create(filename)
                    theResponse = theRequest.GetResponse
                    totallength = theResponse.ContentLength
                    remaintotallength = theResponse.ContentLength

                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
                theResponse.GetResponseStream.Close()
            Next j

        End If


        countUpdatedFiles = ds.Tables(0).Rows.Count
        If countUpdatedFiles >= 0 Then
            countUpdatedFiles = countUpdatedFiles - 1
            For j = 0 To countUpdatedFiles


                filename = strTargetPath & "/" & ds.Tables(0).Rows(j)(0)
                whereToSave = strDestinationPath & "\" & ds.Tables(0).Rows(j)(0)

                'Creating the request and getting the response
                Dim theResponse As HttpWebResponse
                Dim theRequest As HttpWebRequest
                Try 'Checks if the file exist

                    theRequest = WebRequest.Create(filename)
                    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, 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
                    Dim totalpercent As Short = (nRead * 100) / totallength

                    Me.Invoke(safedelegate, length, nRead, percent, totalpercent, 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

                    'Close the streams
                    theResponse.GetResponseStream.Close()
                    writeStream.Close()
                Loop

 
            Next j

            Dim completeDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
            Me.Invoke(completeDelegate, False)

        End If


            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





    End Sub
0
Comment
Question by:togo413
  • 2
  • 2
5 Comments
 

Author Comment

by:togo413
Comment Utility
I need to do something like game client down files from server.
Seem http got limitation , do I need to use win sock  ?
Please advice me
0
 
LVL 18

Expert Comment

by:jcoehoorn
Comment Utility
You don't need to go as low level as winsock.  You will want to move away from http.  Set up an ftp site on your server, and in your code instead of httpwebrequest/httpwebresponse look at ftpwebrequest and ftpwebresponse.
0
 
LVL 27

Expert Comment

by:VBRocks
Comment Utility
Here's an example of how to programmatically perform a download, you can call it as many times as
necessary, and it's very quick:

    Public Sub DownloadFile(ByVal objectToDownload As String, _
        ByVal pathToSaveTo As String)

        'Download the webpage to our temporary XML file
        Dim webClient As New System.Net.WebClient
        webClient.DownloadFile(objectToDownload, pathToSaveTo)

    End Sub


'Here's an example of calling the above:
        'Set our webpage (this is an actual webpage with XML data on it - go ahead and view it)
        Dim myWebPage As String = "http://www.w3schools.com/xml/guestbook.asp"

        'Set our temporary XML page that we will download to
        Dim myXMLPage As String = "c:\temp\myXMLpage.xml"

        DownloadFile(myWebPage, myXMLPage)

        MsgBox("Download complete")

0
 

Author Comment

by:togo413
Comment Utility
Hi VBRocks :

I try your approach before earlier. But with this,  i can't perform checking on the file size before i download.
But using the code above, i can do it.
Any idea ?
0
 
LVL 27

Accepted Solution

by:
VBRocks earned 500 total points
Comment Utility
Here's a function for you that you can use to check the length before downloading:

    Public Function GetLength(ByVal path As String) As Int32

        Dim length As Int32 = -1

        ' Create a 'WebRequest' with the specified url.    
        Dim myWebRequest As Net.WebRequest = Net.WebRequest.Create(path)

        ' Send the 'WebRequest' and wait for response.
        Dim myWebResponse As Net.WebResponse = myWebRequest.GetResponse()

        length = myWebResponse.ContentLength

        myWebResponse.Close()

        Return length

    End Function


'Access it like this:
        Dim length As Int32 = GetLength("http://www.w3schools.com/xml/guestbook.asp")
        MsgBox(length.ToString())

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now