6

这段代码:

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 错误。

我决定异步下载文件:

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 块不会触发。

4

2 回答 2

6

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

链接中有很好的例子。

于 2013-05-05T18:57:04.847 回答
4

你可以试试这段代码:

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;
}
于 2014-12-09T10:29:53.083 回答