Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a Url is absolute or relative from vb [duplicate]

Tags:

.net

vb.net

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

like image 236
Ben Avatar asked Feb 04 '10 16:02

Ben


People also ask

How do you know if a URL is relative or absolute?

The idea here is to still provide for protocol-relative absolute URLs and while extending existing functionality of detecting absolute URLs without requiring a check for the double forward slashes ( // ). Thus, r. test('mailto:[email protected]') === true , r. test('https:example.com') === true , and so forth.

Is URL absolute?

An absolute URL contains all the information necessary to locate a resource. A relative URL locates a resource using an absolute URL as a starting point. In effect, the "complete URL" of the target is specified by concatenating the absolute and relative URLs.

Is URL relative?

A relative URL is a URL that only includes the path. The path is everything that comes after the domain, including the directory and slug. Because relative URLs don't include the entire URL structure, it is assumed that when linking a relative URL, it uses the same protocol, subdomain and domain as the page it's on.


3 Answers

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
like image 55
bdukes Avatar answered Oct 06 '22 08:10

bdukes


Determine if Absolute or Relative URL has simpler answer

bool IsAbsoluteUrl(string url) 
        { 
            Uri result; 
            return Uri.TryCreate(url, UriKind.Absolute, out result);                 
        } 
like image 40
Michael Freidgeim Avatar answered Oct 06 '22 10:10

Michael Freidgeim


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;
}
like image 36
Rubens Farias Avatar answered Oct 06 '22 09:10

Rubens Farias