13

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(); 
}
PiZzL3
  • 2,092
  • 4
  • 22
  • 30
  • You've probably caught this by now, but you have an extra 't' in your url. For anyone else who might be trying to copy-paste the solutions, make sure you change it to "http" or "https" – computerGuyCJ Jun 16 '17 at 17:51

4 Answers4

14

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.

Community
  • 1
  • 1
Greg
  • 23,155
  • 11
  • 57
  • 79
  • Oh wow.. that's good info. I was just under the "assumption" that it was a different name for the same thing (dumb me..). – PiZzL3 Apr 12 '11 at 00:54
  • @PiZzL3 - I wasn't aware of the difference myself until I researched it (to write my answer to the question I linked to). See my edit above for testing the value of `Scheme`. – Greg Apr 12 '11 at 00:56
  • @PiZzL3 - I don't know what other gotchas there might be. Invalid servers come to mind, but you probably won't know if a server is valid or not until you try to access it. – Greg Apr 12 '11 at 01:11
8

Technically, htttp://www.google.com is a properly formatted URL, according the URL specification. The NotSupportedException was thrown because htttp isn't a registered scheme. If it was a poorly-formatted URL, you would have gotten a UriFormatException. If you just care about HTTP(S) URLs, then just check the scheme as well.

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
4

@Greg's solution is correct. However you can steel using URI and validate all protocols (scheme) that you want as valid.

public static bool Url(string p_strValue)
{
    if (Uri.IsWellFormedUriString(p_strValue, UriKind.RelativeOrAbsolute))
    {
        Uri l_strUri = new Uri(p_strValue);
        return (l_strUri.Scheme == Uri.UriSchemeHttp || l_strUri.Scheme == Uri.UriSchemeHttps);
    }
    else
    {
        return false;
    }
}
equiman
  • 7,810
  • 2
  • 45
  • 47
-2

This Code works fine for me to check a Textbox have valid URL format

if((!string.IsNullOrEmpty(TXBProductionURL.Text)) && (Uri.IsWellFormedUriString(TXBProductionURL.Text, UriKind.Absolute)))
{
     // assign as valid URL                
     isValidProductionURL = true; 

}
Nazik
  • 8,696
  • 27
  • 77
  • 123
S.Roshanth
  • 1,499
  • 3
  • 25
  • 36