[英]How to catch 404 WebException for WebClient.DownloadFileAsync
This code: 这段代码:
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);
}
downloads file and informs if 404 error occured. 下载文件并通知是否发生404错误。
I decided to download files asynchronously: 我决定异步下载文件:
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);
}
Now this catch block does not fire if server returns a 404 error and WebClient produces an empty file. 现在,如果服务器返回404错误并且WebClient生成一个空文件,则此catch块不会触发。
You need to handle the DownloadFileCompleted event and check the Error
property of the AsyncCompletedEventArgs . 您需要处理DownloadFileCompleted事件并检查AsyncCompletedEventArgs的
Error
属性。
There are good examples in the links. 链接中有很好的例子。
You can try this code: 你可以试试这段代码:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.