Home > C#, Misc, Windows 8 > Windows 8 – Validate URL

Windows 8 – Validate URL

Sample code for validating URL’s.

Invoke below method and pass the URL.

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

        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";
        //Getting 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;
}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: