0

I have a code for checking if response is error 404 an if it is set an image from resources that code works fine before but now it is giving error I don't know why. Here is the code

 try
        {
            picture.Load(img);
        }
        catch (WebException we)
        {
            HttpWebResponse errorResponse = we.Response as HttpWebResponse;
            if (errorResponse.StatusCode == HttpStatusCode.NotFound)
            {
                Image image = Properties.Resources.Error_404;
                picture.Image = image;
            }
        }

the HttpStatusCode,NotFound is what gives error Object reference not set to an instance of an object C#.

P.RAO
  • 41
  • 8
  • No, `HttpStatusCode.NotFound` will *not* give that error... but `errorResponse.StatusCode` certainly will, if `errorResponse` is null, which it will be if `we.Response` isn't an `HttpWebResponse`. *Any* time you use `as`, you need to consider what you want to happen if the result is `null`. – Jon Skeet Oct 21 '16 at 05:57
  • 1
    Check for errorResponse object as well. if (errorResponse == null || errorResponse.StatusCode == HttpStatusCode.NotFound) – kashi_rock Oct 21 '16 at 06:00
  • but it was working fine before for the same request and now it is giving this error. :/ – P.RAO Oct 21 '16 at 06:02
  • Can't you debug and check which object is null? – kashi_rock Oct 21 '16 at 06:04
  • @kashi_rock it works if(errorResponse == null || errorResponse.StatusCode == HttpStatusCode.NotFound). Thanks for quick response. – P.RAO Oct 21 '16 at 07:33
  • Please post your own answer and mark as answered – kashi_rock Oct 21 '16 at 08:22
  • I don't know how to do that. – P.RAO Oct 21 '16 at 10:43

0 Answers0