Ala Ala - 3 months ago 22
ASP.NET (C#) Question

Handling the HttpWebResponse before throwing exception for (404) File Not Found

Is there any way to process the

HttpWebResponse.GetResponse()
before throwing exception for (404) File Not Found?

I have a huge amount of images to download, and using Try..catch to handle the exceptions of file not found will make the performance very bad.

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

EZI EZI
Answer

You can use HttpClient, it doesn't throw exception on 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;
Comments