Is there a URL validator on .Net?

Viewed 30405

Is there a method to validate URLs in .Net, ASP.Net, or ASP.Net MVC?

6 Answers

You can use the Uri.TryCreate to validate an URL:

public bool IsValidUri(string uri)
{
    Uri validatedUri;
    return Uri.TryCreate(uri, UriKind.RelativeOrAbsolute, out validatedUri);
}

The comments suggest that TryCreate just moves the exception handling one level down. However, I checked the source code and found that this is not the case. There is no try/catch inside TryCreate, it uses a custom parser which should not throw.

In case you need the nice code in VB.Net from Arjan

    'Validates a URL.
    Function ValidateUrl(url As String) As Boolean
        Dim validatedUri As Uri = Nothing
        If (Uri.TryCreate(url, UriKind.Absolute, validatedUri)) Then
            Return (validatedUri.Scheme = Uri.UriSchemeHttp Or validatedUri.Scheme = Uri.UriSchemeHttps)
        End If
        Return False
    End Function

A faster way (probably) than using try/catch functionality would be to use Regex. If you had to validate 1000s of URLs catching the exception multiple times would be slow.

Here's a link to sample Regex- use Google to find more.

static bool IsValidUri(string urlString) {
   try {
      new Uri(urlString);
      return true;
   } catch {
      return false;
   }
}
Related