Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Need help on HttpWebRequest ,HttpWebResponse coding urgent..... Cannot loop to download multiple files

Posted on 2007-11-17
4
653 Views
Last Modified: 2013-11-26
Hi  all,

Please help. I cannot download the files in loop. !st loop work perfect. Second loop the process die at
length = theResponse.ContentLength . Plese help me correct my code. I check already, the loop no problem.
Public Sub ChangeTexts(ByVal length As Long, ByVal position As Integer, ByVal percent 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
 
 
    End Sub
 
 
 
    Private Sub backgroundwork()
        Dim ServerPath As String
        Dim strTargetPath As String
        Dim strDestinationPath 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
            countUpdatedFiles = countUpdatedFiles - 1
 
            'Creating the request and getting the response
            Dim theResponse As HttpWebResponse
            Dim theRequest As HttpWebRequest
            Dim err As String
 
 
            For j = 0 To countUpdatedFiles
                Dim length As Long
                filename = strTargetPath & "/" & ds.Tables(0).Rows(j)(0)
                whereToSave = strDestinationPath & "\" & ds.Tables(0).Rows(j)(0)
       
                Try 'Checks if the file exist
 
                    theRequest = WebRequest.Create(filename)
                    theResponse = theRequest.GetResponse
 
                    length = theResponse.ContentLength 'Size of the response (in bytes)
                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)
                    err = ex.ToString()
                    Exit Sub
                End Try
 
                Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
                Me.Invoke(safedelegate, length, 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
                nRead = 0
                '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
                    'ori
                    Dim percent As Short = (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
 
                    'Close the streams
 
                Loop
                theResponse.GetResponseStream.Close()
                writeStream.Close()
 
            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

Open in new window

0
Comment
Question by:togo413
  • 2
  • 2
4 Comments
 
LVL 82

Accepted Solution

by:
hielo earned 500 total points
ID: 20304471
Try opening and closing the response object for every file. Look at the following;
http://jstawski.com/archive/2007/02/22/downloading-multiple-files-from-an-ftp-using-wildcards.aspx
0
 

Author Comment

by:togo413
ID: 20305108
You are my lucky star. I solve this nearly 2 nite d.
Thanks hielo.

I got close theResponse.GetResponseStream.Close() after every loop.
But din theResponse.Close

After add in, it works perfect.
0
 
LVL 82

Expert Comment

by:hielo
ID: 20305153
Nice to hear it worked for you.
>tonight
Where are you?
0
 

Author Comment

by:togo413
ID: 20305347
Me  haha office lo. Me from Malaysia, now in Kuala Lumpur office. now is midnite 4:40 am
0

Featured Post

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

839 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