如何为WebClient.DownloadFileAsync捕获404 WebException [英] How to catch 404 WebException for WebClient.DownloadFileAsync

查看:233
本文介绍了如何为WebClient.DownloadFileAsync捕获404 WebException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

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);
}

下载文件并通知是否发生404错误.

downloads file and informs if 404 error occured.

我决定异步下载文件:

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);
}

现在,如果服务器返回404错误并且WebClient生成一个空文件,则此catch块不会触发.

Now this catch block does not fire if server returns a 404 error and WebClient produces an empty file.

推荐答案

您需要处理已完成的

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

链接中有很好的例子.

这篇关于如何为WebClient.DownloadFileAsync捕获404 WebException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆