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,
You can check the e.Error value.
private void wc_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
if (e.Error != null)
{
if (e.Error is WebException)
Console.WriteLine("Web Exception {0}", ((WebException)e.Error).Message);
else
Console.WriteLine("Web Exception {0}", e.Error.Message);
}
else if (e.Cancelled)
Console.WriteLine("File cancelled");
else
Console.WriteLine("File completed");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With