【问题标题】:How to catch 404 WebException for WebClient.DownloadFileAsync如何为 WebClient.DownloadFileAsync 捕获 404 WebException
【发布时间】:2013-04-29 13:38:38
【问题描述】:

这段代码:

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

【问题讨论】:

    标签: c# .net asynchronous http-status-code-404 webclient


    【解决方案1】:

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

    链接中有很好的例子。

    【讨论】:

    • 并且每次都删除一个空文件?
    • @Paul:是的,如果有错误。 DownloadFileAsync 显然会打开一个文件以准备写入。它在完成后关闭文件,错误或否。如果您不想要该文件,请将其删除。
    【解决方案2】:

    你可以试试这个代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多