C# webrequests->getresponse casts exception instead of returning status code

60 Views Asked by At

I'm attempting to make an image scraper, now for some pages the image was not specified so i wanted to parse my output based on the status code i receive when accessing the page but when i attempt to pare my status code i get an exception instead of the status code if the page was not found, any idea why this happends?

        if (gameinfo != null)
            if (!string.IsNullOrEmpty(gameinfo.image_uri))
                try
                {
                    using (System.Net.WebClient client = new System.Net.WebClient())
                    {
                        // Build Uri and attempt to fetch a response.
                        UriBuilder uribuild = new UriBuilder(gameinfo.image_uri);
                        WebRequest request = WebRequest.Create(uribuild.Uri);
                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                        switch (response.StatusCode)
                        {
                            // Page found and valid entry.
                            case HttpStatusCode.OK:
                                using (Stream stream = client.OpenRead(uribuild.Uri))
                                {
                                    Console.WriteLine(String.Format("Downloading {0}", uribuild.Uri));
                                    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream);
                                    bitmap.Save(System.IO.Path.Combine(rom_root, String.Format("{0}.jpg", file_name.Substring(2).Split('.').First())));
                                }
                                break;
                            // Unspecified status codes.
                            default:
                                Console.WriteLine("Unspecified status code found, aborting...");
                                break;
                        }
                    }
                } catch(System.Net.WebException ex)
                {
                    // Should be moved to switch with HttpStatusCode.NotFound ^
                    Console.WriteLine("Image page not found.");
                }
1

There are 1 best solutions below

1
On

That's just how the GetResponse() implementation is. If the response is anything other than a success, a WebException is thrown.

I agree, I find it a bit odd - it would be nice if it was optional behaviour at least. Thankfully, you can read the status code from the WebException which is being thrown:

....
catch (WebException e)
{
    using (WebResponse response = e.Response)
    {
        HttpWebResponse httpResponse = (HttpWebResponse) response;
        var statusCode = httpResponse.StatusCode;
        // Do stuff with the statusCode
    }
}