【发布时间】:2014-07-08 17:10:40
【问题描述】:
在抛出 (404) File Not Found 异常之前,有什么方法可以处理 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;
}
}
【问题讨论】:
标签: c# asp.net download webclient httpwebresponse