Url Exists Snippet

Here follows a code snippet that will verify if an url exists. It creates a web request using HEAD and tries to get its response. HEAD as request method will boost performance of the request, since no content is downloaded. In some cases the remote server exists but doesn´t allow HEAD as request method and will return a web exception with status code 405 – method not allowed. Therefore we try again using GET as request method.

Tip: To test this snippet or your own code deals with varying status codes, you can use the following service to generate different HTTP status codes.

static bool UrlExists(string url)
{
    try
    {
        var request = WebRequest.Create(url);

        // HEAD as request method will boost the performance of the 
        // request, as no content is downloaded.
        request.Method = WebRequestMethods.Http.Head;

        using (var response = (HttpWebResponse)request.GetResponse())
        {
            return (response.StatusCode == HttpStatusCode.OK);
        }
    }
    catch (UriFormatException)
    {
        // Invalid url so break here...
        return false;
    }
    catch (WebException wex)
    {
        using (var responseException = wex.Response as HttpWebResponse)
        {
            if (responseException != null 
                    && responseException.StatusCode == HttpStatusCode.MethodNotAllowed)
            {
                // Try again using GET as request method, because it is possible 
                // that the remote server doesn´t allow HEAD and will return an
                // error like: (405) Method Not Allowed.
                try
                {
                    var request = WebRequest.Create(url);
                    request.Method = WebRequestMethods.Http.Get;

                    using (var response = (HttpWebResponse)request.GetResponse())
                    {
                        return (response.StatusCode == HttpStatusCode.OK);
                    }
                }
                catch
                {
                    return false;
                }
            }
        }
        return false;
    }
    catch (Exception)
    {
        // So we have finally reached the very end;
        return false;
    }
}