如何为WebClient.DownloadFileAsync捕获404 WebException

Pau*_*aul 4 .net c# asynchronous webclient http-status-code-404

这段代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

我决定异步下载文件:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

Jim*_*hel 6

您需要处理DownloadFileCompleted事件并检查AsyncCompletedEventArgsError属性.

链接中有很好的例子.