I wasn't suggesting that you add a Try...Catch block to your DownloadFileCompleted event handler. The exception handler is built into WebClient class. The WebClient tries to download the file and, if an exception is thrown, it catches it. Once the download is complete, either successfully or unsuccessfully, the DownloadFileCompleted event is raised. In the event handler, you check whether an exception occurred or not and you proceed accordingly, e.g.
vb.net Code:
Imports System.Net
Imports System.ComponentModel
Public Class Form1
Private WithEvents downloader As New WebClient
Private Sub downloadButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles downloadButton.Click
If Not Me.downloader.IsBusy Then
MessageBox.Show("A download is already in progress.",
"Download In Progress",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
Else
Try
Me.downloadButton.Enabled = False
Dim remoteAddress As String = Me.remoteAddressTextBox.Text
Dim localAddress As String = Me.localAddressTextBox.Text
Dim userToken As String() = New String() {remoteAddress, localAddress}
Me.downloader.DownloadFileAsync(New Uri(remoteAddress), localAddress, userToken)
Catch ex As Exception
Me.downloadButton.Enabled = True
MessageBox.Show(ex.Message, "Download Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
Private Sub downloader_DownloadFileCompleted(ByVal sender As Object,
ByVal e As AsyncCompletedEventArgs) Handles downloader.DownloadFileCompleted
Me.downloadButton.Enabled = True
If e.Error Is Nothing Then
Dim addresses As String() = DirectCast(e.UserState, String())
MessageBox.Show(String.Format("The file '{0}' was successfully downloaded to '{1}'.",
addresses(0),
addresses(1)),
"Download Complete",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
Else
MessageBox.Show(e.Error.Message, "Download Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
End Class
With regards to the NetworkAvailabilityChanged event, there may not be any reason to handle it as the DownloadFileCompleted event will still provide exception details, so you may end up double-reporting to the user. If you do still want to handle it, you can check the IsBusy property of your WebClient to determine whether a file is being downloaded.