确定一个地址是绝对的还是相对的从VB地址、VB

2023-09-04 08:12:35 作者:后来,无人像你

我试图确定在VB中如果URL是绝对的还是相对的。我敢肯定,必须有一些库可以做到这一点,但我不知道它。基本上我需要能够分析一个字符串,如相对/路径和或http://www.absolutepath.com/subpage'并确定它是否是绝对或相对的。先谢谢了。

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

推荐答案

您可以使用Uri.IsWellFormedUriString方法,它需要一个 UriKind 作为参数,指定无论你是检查绝对或相对的。

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