C#, Is there a better way to verify URL formatting than IsWellFormedUriString?

PiZzL3 picture PiZzL3 · Apr 12, 2011 · Viewed 18.6k times · Source

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 NotSupportedExceptionlater 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(); 
}

Answer

Greg picture Greg · Apr 12, 2011

The 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 to http or https.