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
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.
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.
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.
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
Determine if Absolute or Relative URL has simpler answer
bool IsAbsoluteUrl(string url)
{
Uri result;
return Uri.TryCreate(url, UriKind.Absolute, out result);
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With