First, use the using statement in the answer - this way you will manage it no matter what happens.
Now, if a WebException , you can catch this and look at WebException.Response to find out the status code and any data sent:
WebRequest request = WebRequest.Create(URL); request.Method = "HEAD"; try { using (WebResponse response = request.GetResponse()) { // Use data for success case } } catch (WebException ex) { HttpWebResponse errorResponse = (HttpWebResponse) ex.Response; HttpStatusCode status = errorResponse.StatusCode; // etc }
source share