如何捕获 WebClient.DownloadFileAsync 的 404 WebException 错误

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块不会触发。
2个回答

6

1
每次删除一个空文件? - Paul
@Paul:是的,如果出现错误。显然 DownloadFileAsync 打开一个文件以准备写入。完成后无论是否有错误,都会关闭该文件。如果你不想要这个文件,就删除它。 - Jim Mischel

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接