尝试从FTP下载文件以获得我计划实现backgroundWorker的下载进度,下面的代码将显示UI中kb下载的进度、速度、数量,下面是我用backgroundWorker_doWork编写的代码
'Creating the request and getting the response
Dim theResponse As FtpWebResponse
Dim theRequest As FtpWebRequest
Try
'Checks if the file exist
theRequest = WebRequest.Create(Me.txtFileName.Text)
theResponse = theRequest.GetResponse
Catch ex As Exception
MessageBox.Show("An error occurred while downloading file. Possible 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) '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
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
theResponse.GetResponseStream.Close()
writeStream.Close()
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
Dim completeDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
Me.Invoke(completeDelegate, False)
Dim length As Long = theResponse.ContentLength获取-1ftp://username:mypassword@ftp.drivehq.com/masters/5/party/party.csv
ftp Url正在传递的下载文件,这里party.csv是要下载的文件,注意:问题是当获取要下载的文件的文件大小时,在我的例子中是party,csv,Dim length As Long = theResponse.ContentLength的大小。在这里,theResponse.ContentLength获取-1文件的实际大小是420KB,如果我更改Dim length As Long =430080(420kb=430080bytes),代码将工作发布于 2014-06-19 06:44:37
找到下面的解决方案,以获得找到file's size的精确方法
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(Me.txtFileName.Text), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.GetFileSize
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
Dim fileSize As Long = response.ContentLengthhttps://stackoverflow.com/questions/24299882
复制相似问题