9

I'm trying to determine in vb if a URL is absolute or relative. I'm sure there has to be some library that can do this but I'm not sure which. Basically I need to be able to analyze a string such as 'relative/path' and or 'http://www.absolutepath.com/subpage' and determine whether it is absolute or relative. Thanks in advance.

-Ben

Ben
  • 2,058
  • 9
  • 29
  • 39

3 Answers3

18

You can use the Uri.IsWellFormedUriString method, which takes a UriKind as an argument, specifying whether you're checking for absolute or relative.

bool IsAbsoluteUrl(string url) {
    if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) {
        throw new ArgumentException("URL was in an invalid format", "url");
    }
    return Uri.IsWellFormedUriString(url, UriKind.Absolute);
}

IsAbsoluteUrl("http://www.absolutepath.com/subpage"); // true
IsAbsoluteUrl("/subpage"); // false
IsAbsoluteUrl("subpage"); // false
IsAbsoluteUrl("http://www.absolutepath.com"); // true
bdukes
  • 152,002
  • 23
  • 148
  • 175
  • 4
    If you're checking to see if the URL will send the user to a different domain this fails. It doesn't handle protocol-relative URLs. `//gmail.com` is considered relative, not absolute, to System.Uri. Browsers will assume the current scheme/protocol, but System.Uri doesn't handle that case. – yzorg Aug 14 '14 at 22:50
4

Determine if Absolute or Relative URL has simpler answer

bool IsAbsoluteUrl(string url) 
        { 
            Uri result; 
            return Uri.TryCreate(url, UriKind.Absolute, out result);                 
        } 
Community
  • 1
  • 1
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
  • 2
    Uri.IsWellFormedUriString(url, UriKind.Absolute) is pretty simple, too. Also it's probably faster, since it's not trying to create a new Uri. – Vlad Iliescu Jun 29 '13 at 19:44
1

Try this:

Uri uri = new Uri("http://www.absolutepath.com/subpage");
Console.WriteLine(uri.IsAbsoluteUri);

Edit: If you're not sure that address is well-formed, you should to use:

static bool IsAbsolute(string address, UriKind kind)
{
    Uri uri = null;
    return Uri.TryCreate(address, kind, out uri) ? 
        uri.IsAbsoluteUri : false;
}
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
  • If you're checking to see if the URL will send the user to a different domain this fails. It doesn't handle protocol-relative URLs. `//gmail.com` is considered relative, not absolute, to System.Uri. – yzorg Aug 14 '14 at 22:51