tags:

views:

183

answers:

2

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

+2  A: 

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
This is exactly what I needed. Thanks!
Ben
+1  A: 

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