Is there a better/more accurate/stricter method/way to find out if a URL is properly formatted?
Using:
bool IsGoodUrl = Uri.IsWellFormedUriString(url, UriKind.Absolute);
Doesn't catch everything. If I type htttp://www.google.com
and run that filter, it passes. Then I get a NotSupportedException
later when calling WebRequest.Create
.
This bad url will also make it past the following code (which is the only other filter I could find):
Uri nUrl = null;
if (Uri.TryCreate(url, UriKind.Absolute, out nUrl))
{
url = nUrl.ToString();
}
@Greg's solution is correct. However you can steel using URI and validate all protocols (scheme) that you want as valid.
This Code works fine for me to check a
Textbox
have valid URL formatThe reason
Uri.IsWellFormedUriString("htttp://www.google.com", UriKind.Absolute)
returns true is because it is in a form that could be a valid Uri. URI and URL are not the same.See: What's the difference between a URI and a URL?
In your case, I would check that
new Uri("htttp://www.google.com").Scheme
was equal tohttp
orhttps
.Technically,
htttp://www.google.com
is a properly formatted URL, according the URL specification. TheNotSupportedException
was thrown becausehtttp
isn't a registered scheme. If it was a poorly-formatted URL, you would have gotten aUriFormatException
. If you just care about HTTP(S) URLs, then just check the scheme as well.