C# 在为(404)文件引发异常之前处理HttpWebResponse未找到
在为未找到的(404)文件引发异常之前,是否有任何方法可以处理C# 在为(404)文件引发异常之前处理HttpWebResponse未找到,c#,asp.net,download,webclient,httpwebresponse,C#,Asp.net,Download,Webclient,Httpwebresponse,在为未找到的(404)文件引发异常之前,是否有任何方法可以处理HttpWebResponse.GetResponse() 我有大量的图片要下载,使用Try..catch处理未找到文件的异常会使性能非常差 private bool Download(string url, string destination) { try { if (RemoteFileExists("http://www.example.com/FileNotFound.png")
HttpWebResponse.GetResponse()
我有大量的图片要下载,使用Try..catch处理未找到文件的异常会使性能非常差
private bool Download(string url, string destination)
{
try
{
if (RemoteFileExists("http://www.example.com/FileNotFound.png")
{
WebClient downloader = new WebClient();
downloader.DownloadFile(url, destination);
return true;
}
}
catch(WebException webEx)
{
}
return false;
}
private bool RemoteFileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
//Here is my question, When the image's not there,
//the following line will throw an exception, How to avoid that?
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TURE if the Status code == 200
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false.
return false;
}
}
您可以使用,它不会在404上引发异常:
HttpClient c = new HttpClient();
var resp = await c.SendAsync(new HttpRequestMessage(HttpMethod.Head, "http://www.google.com/abcde"));
bool ok = resp.StatusCode == HttpStatusCode.OK;
使用<代码> HTTPcli客< /代码>发送<代码>异步> <代码>请求将解决(404文件未找到)的异常,因此我将它视为对这个问题的回答,然而,我想在这里分享我的性能测试。我已经测试了以下两种方法来下载50000张图像:
方法1try
{
// I will not check at all and let the the exception happens
downloader.DownloadFile(url, destination);
return true;
}
catch(WebException webEx)
{
}
方法2
try
{
// Using HttpClient to avoid the 404 exception
HttpClient c = new HttpClient();
var resp = await c.SendAsync(new HttpRequestMessage(HttpMethod.Head,
"http://www.example.com/img.jpg"));
if (resp.StatusCode == HttpStatusCode.OK)
{
downloader.DownloadFile(url, destination);
return true;
}
}
catch(WebException webEx)
{
}
在我的测试中,要下载的50000个图像中有144个图像不可用,方法1的性能比方法2快3倍