VS C# 2005
I am using the code below to upload a file Async using the web client. However, I am not sure that I can catch the exception if there is a problem. Because the wc.UpLoadFileAsync would return immediately. So it seems pointless to put the try...catch in there.
So to test, I deliberately created an error to see what would happen if I put in an incorrect URL. However, I get this in my debug output window.
A first chance exception of type 'System.Net.WebException' occurred in System.dll
File completed
So it doesn’t fire in the try...catch. And it still fires the UploadFileCompleted method
private void upload_config_to_server()
{
Uri url = new Uri("http://10.10.10.3/softphone/config.xml");
WebClient wc = new WebClient();
if (!wc.IsBusy)
{
wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
wc.UploadFileCompleted += new UploadFileCompletedEventHandler(wc_UploadFileCompleted);
try
{
wc.UploadFileAsync(url, "PUT", "config.xml");
}
catch (WebException webex)
{
Console.WriteLine("Web Exception {0}", webex.Message);
}
catch (Exception ex)
{
Console.WriteLine("Exception {0}", ex.Message);
}
}
}
private void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
Console.WriteLine("Bytes uploaded {0}", e.BytesSent);
}
private void wc_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
Console.WriteLine("File completed");
}
Is there a correct way to handle this. I just want to show a message box to the user to display the reason why the upload file failed. However, as the uploaded file can be big it could take several seconds to upload it. So I need to have the Async to prevent the UI freezing up.
Many thanks for any suggestion,
Since the call is asynchronous, your thread will continue executing and exit the
try..catchblock, so the exceptions will not occur there. Instead, you should check theErrorproperty on the eventargs object in theUploadFileCompletedevent handler. If there is an exception in the process, theErrorproperty will contain the exception object. Also, I think it’s a good idea to detach the event handlers there:This is a common approach in asynchronous programming; the asynchronous method catches the exception and stores it somewhere where you can examine it after the asynchronous call has completed.