Skip to content
Amal Hashim
All posts
Snippet

Windows 8 - Validate a URL

An async C# method that checks a URL is well formed and that the server answers, using a HEAD request.

1 min read#.NET#C##Windows

This method checks that a URL has a valid pattern and that the server responds. Call it and pass the URL.

It sends a HEAD request, so the body is not downloaded. You can use GET too. A 403 Forbidden response counts as valid, because the address exists even if access is refused.

csharp
private async Task<bool> UriExists(string url)
{
    try
    {
        // Validate whether url has a valid uri pattern
        if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
            return false;

        // Create the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        // Set the request method to HEAD, you can also use GET
        request.Method = "HEAD";
        // Get the web response
        HttpWebResponse response =
            await request.GetResponseAsync() as HttpWebResponse;

        if (response.StatusCode == HttpStatusCode.OK ||
            response.StatusCode == HttpStatusCode.Forbidden)
            return true;
    }
    catch (WebException ex)
    {
        HttpWebResponse r = ex.Response as HttpWebResponse;
        if (r.StatusCode == HttpStatusCode.Forbidden)
            return true;
    }
    return false;
}

Example

csharp
bool ok = await UriExists("http://www.microsoft.com"); // true
bool bad = await UriExists("not a url");               // false