How to catch 404 WebException for WebClient.DownloadFileAsync

This code:

try { _wcl.DownloadFile(url, currentFileName); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound) Console.WriteLine("\r{0} not found. ", currentFileName); } 

downloads the file and reports if a 404 error has occurred.

I decided to upload files asynchronously:

 try { _wcl.DownloadFileAsync(new Uri(url), currentFileName); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound) Console.WriteLine("\r{0} not found. ", currentFileName); } 

Now this blocking block does not work if the server returns a 404 error and WebClient creates an empty file.

+4
source share
2 answers

You need to handle the DownloadFileCompleted event and check the Error property AsyncCompletedEventArgs .

There are good examples in the links.

+6
source

You can try this code:

 WebClient wcl; void Test() { Uri sUri = new Uri("http://google.com/unknown/folder"); wcl = new WebClient(); wcl.OpenReadCompleted += onOpenReadCompleted; wcl.OpenReadAsync(sUri); } void onOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error != null) { HttpStatusCode httpStatusCode = GetHttpStatusCode(e.Error); if (httpStatusCode == HttpStatusCode.NotFound) { // 404 found } } else if (!e.Cancelled) { // Downloaded OK } } HttpStatusCode GetHttpStatusCode(System.Exception err) { if (err is WebException) { WebException we = (WebException)err; if (we.Response is HttpWebResponse) { HttpWebResponse response = (HttpWebResponse)we.Response; return response.StatusCode; } } return 0; } 
+3
source

Source: https://habr.com/ru/post/1479262/


All Articles