views:

27

answers:

2

In ASP.net what's the best way I can parse a string to determine if it's a valid URL?

+4  A: 

Call Uri.TryCreate.

For example:

Uri parsedUri;
if (!Uri.TryCreate(input, UriKind.Absolute, out parsedUri)) {
    //Bad!
}
SLaks
A: 

Use a regular expression

m.edmondson
_No_, **don't**.
SLaks
Any reasons why?
m.edmondson
Most regular expressions that you'll find will not fully conform to the URL spec. (eg, inline basic auth, `.museam`, full sets of domain name characters)
SLaks
So why not sit down with the spec and write one that does?
m.edmondson
Because you'll end up with an enormous and complicated regex (which you'll need to debug) that duplicates functionality already available in `Uri.TryCreate`.
SLaks
Okay fair comment
m.edmondson