A better way to validate URL in C# than try-catch?

Use Uri.TryCreate to create a new Uri object only if your url string is a valid URL. If the string is not a valid URL, TryCreate returns false.

string myString = "http://someUrl";
Uri myUri;
if (Uri.TryCreate(myString, UriKind.RelativeOrAbsolute, out myUri))
{
    //use the uri here
}

UPDATE

TryCreate or the Uri constructor will happily accept strings that may appear invalid, eg "Host: www.stackoverflow.com","Host:%20www.stackoverflow.com" or "chrome:about". In fact, these are perfectly valid URIs that specify a custom scheme instead of "http".

The documentation of the Uri.Scheme property provides more examples like "gopher:" (anyone remember this?), "news", "mailto", "uuid".

An application can register itself as a custom protocol handler as described in MSDN or other SO questions, eg How do I register a custom URL protocol in Windows?

TryCreate doesn't provide a way to restrict itself to specific schemes. The code needs to check the Uri.Scheme property to ensure it contains an acceptable value

UPDATE 2

Passing a weird string like "></script><script>alert(9)</script> will return true and construct a relative Uri object. Calling Uri.IsWellFormedOriginalString will return false though. So you probably need to call IsWellFormedOriginalString if you want to ensure that relative Uris are well formed.

On the other hand, calling TryCreate with UriKind.Absolute will return false in this case.

Interestingly, Uri.IsWellFormedUriString calls TryCreate internally and then returns the value of IsWellFormedOriginalString if a relative Uri was created.


A shortcut would be to use Uri.IsWellFormedUriString:

if (Uri.IsWellFormedUriString(myURL, UriKind.RelativeOrAbsolute))
...

Some examples when using Uri to test a valid URL fails

Uri myUri = null;
if (Uri.TryCreate("Host: www.stackoverflow.com", UriKind.Absolute, out myUri))
{
}

  myUri = null;
if (Uri.TryCreate("Accept: application/json, text/javascript, */*; q=0.01", UriKind.Absolute, out myUri))
{
}

  myUri = null;
if (Uri.TryCreate("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0", UriKind.Absolute, out myUri))
{
}

  myUri = null;
if (Uri.TryCreate("DNT: 1", UriKind.Absolute, out myUri))
{
}

I Was surprised to have all this nonsense appear in my listview after validating with the above. But it all passes the validation test.

Now I add the following after the above validation

url = url.ToLower();
if (url.StartsWith("http://") || url.StartsWith("https://")) return true;