Hello,
Right now I'm writing a program that can download a file from the a URL provided in a text box. Here's my code so far.
Here's a screen shot of the layout. The top text box is where you type in the URL, the second is where you type in the file name and the three white bar is a progress bar. When you press the "Download!" button it begins the download.
As of now, when you hit the button, the window locks up and does not respond until the download is complete. Is there a way to use multithreads to make the download work in the background so I could make a Cancel button work in the program? I did my research and found a little method called RunWorkerAsync. I read up on it but was baffled on how to actually use it in my situation.
Any suggestions?
Thanks for your help in advance.
Right now I'm writing a program that can download a file from the a URL provided in a text box. Here's my code so far.
VB.NET:
Imports System.IO
Imports System.Net
Public Class Download
Delegate Sub updateProgressBarDelegate(ByVal percent As Integer)
Private Sub downloadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles downloadButton.Click
downloadFile(url.Text, fileName.Text)
End Sub
Private Sub downloadFile(ByVal url As String, ByVal fileName As String)
Dim webRequest As HttpWebRequest
Dim webResponse As HttpWebResponse
Dim writeStream As New IO.FileStream(fileName, IO.FileMode.Create)
webRequest = HttpWebRequest.Create(url)
webResponse = webRequest.GetResponse()
Dim fileSize As Integer
fileSize = webResponse.ContentLength
Dim nRead As Integer
nRead = 0
Dim buffer(4096) As Byte
Dim blockSize As Integer
Dim tempStream As New MemoryStream
Dim updateProgressBarDelegateSafe As New updateProgressBarDelegate(AddressOf updateProgressBar)
Invoke(updateProgressBarDelegateSafe, 0)
Do
Dim readBytes(4095) As Byte
blockSize = writeStream.Read(buffer, 0, 4096)
Dim bytesread As Integer = webResponse.GetResponseStream.Read(readBytes, 0, 4096)
nRead += bytesread
If bytesread = 0 Then Exit Do
writeStream.Write(readBytes, 0, bytesread)
Dim percent As Short = (nRead * 100) / fileSize
Invoke(updateProgressBarDelegateSafe, percent)
Loop
webResponse.Close()
writeStream.Close()
End Sub
Public Sub updateProgressBar(ByVal percent As Integer)
downloadProgress.Value = percent
End Sub
End Class
Here's a screen shot of the layout. The top text box is where you type in the URL, the second is where you type in the file name and the three white bar is a progress bar. When you press the "Download!" button it begins the download.
As of now, when you hit the button, the window locks up and does not respond until the download is complete. Is there a way to use multithreads to make the download work in the background so I could make a Cancel button work in the program? I did my research and found a little method called RunWorkerAsync. I read up on it but was baffled on how to actually use it in my situation.
Any suggestions?
Thanks for your help in advance.