Class Download
#Region "Events"
Public Event DownloadStarted As EventHandler
Public Event DownloadCompleted As EventHandler
Public Event DownloadProgressChanged As EventHandler
Public Event DownloadAborted As EventHandler
Public Event DownloadPaused As EventHandler
Public Event DownloadResumed As EventHandler
#End Region
#Region "Attributes"
Private s, d As String
Private b, sec, v As Decimal
Dim t As Threading.Thread, ss As IO.BufferedStream, ds As IO.FileStream, dst As DownStatus
Dim WithEvents tim As New Timer With {.Interval = 1000}
#End Region
#Region "Enums"
Enum DownStatus
NoOperation = 0
Downloading
Paused
Completed
End Enum
#End Region
#Region "Constructors"
Public Sub New(ByVal url As String, ByVal filename As String)
s = url
d = filename
b = 0
sec = 0
t = Nothing
ss = Nothing
ds = Nothing
dst = DownStatus.NoOperation
End Sub
#End Region
#Region "Properties"
Public Property Source() As String
Get
Return s
End Get
Set(ByVal value As String)
s = value
End Set
End Property
Public Property Destination() As String
Get
Return d
End Get
Set(ByVal value As String)
d = value
End Set
End Property
Public ReadOnly Property DownloadedBytes() As Decimal
Get
Return b
End Get
End Property
Public ReadOnly Property Seconds() As Decimal
Get
Return sec
End Get
End Property
Public ReadOnly Property Speed() As Decimal
Get
Return v
End Get
End Property
Public ReadOnly Property DownloadStatus() As DownStatus
Get
Return dst
End Get
End Property
#End Region
#Region "Public methods"
Public Sub StartDownload()
t = New Threading.Thread(AddressOf Download)
ss = New IO.BufferedStream(Net.WebRequest.Create(s).GetResponse.GetResponseStream)
ds = New IO.FileStream(d, IO.FileMode.OpenOrCreate)
tim.Start()
t.Start()
dst = DownStatus.Downloading
RaiseEvent DownloadStarted(Me, New EventArgs)
End Sub
Public Sub AbortDownload()
dst = DownStatus.NoOperation
t.Abort()
tim.Stop()
ds.Close()
ss.Close()
RaiseEvent DownloadAborted(Me, New EventArgs)
End Sub
Public Sub PauseDownload()
dst = DownStatus.Paused
t.Suspend()
tim.Stop()
RaiseEvent DownloadPaused(Me, New EventArgs)
End Sub
Public Sub ResumeDownload()
tim.Start()
t.Resume()
dst = DownStatus.Downloading
RaiseEvent DownloadResumed(Me, New EventArgs)
End Sub
#End Region
#Region "Private methods"
Private Sub Download()
While True
Try
ds.WriteByte(ss.ReadByte)
Catch
Exit While
End Try
b += 1
Application.DoEvents()
RaiseEvent DownloadProgressChanged(Me, New EventArgs)
End While
tim.Stop()
ds.Close()
ss.Close()
dst = DownStatus.Completed
RaiseEvent DownloadCompleted(Me, New EventArgs)
End Sub
#End Region
#Region "Private events"
Private Sub tim_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tim.Tick
sec += 1
v = b / sec
End Sub
#End Region
End Class