获得在C#/。NET的URL域名 [英] Get domain name of a url in C# / .NET

查看:138
本文介绍了获得在C#/。NET的URL域名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在code:

string sURL = "http://subdomain.website.com/index.htm";
MessageBox.Show(new System.Uri(sURL).Host);

给我subdomain.website.com

gives me "subdomain.website.com"

但我需要的主域名website.com对任何URL或网页链接。

But I need the main domain "website.com" for any url or web link.

我该怎么办呢?

推荐答案

您可以做到这一点,以获取主机名刚刚过去的两个部分:

You can do this to get just the last two segments of the host name:

string[] hostParts = new System.Uri(sURL).Host.Split('.');
string domain = String.Join(".", hostParts.Skip(Math.Max(0, hostParts.Length - 2)).Take(2));

或者这样:

var host = new System.Uri(sURL).Host;
var domain = host.Substring(host.LastIndexOf('.', host.LastIndexOf('.') - 1) + 1);

此方法会发现包括至少两个域名部分,但也将包括两个字符或中间零件更少:

This method will find include at least two domain name parts, but will also include intermediate parts of two characters or less:

var host = new System.Uri(sURL).Host;
int index = host.LastIndexOf('.'), last = 3;
while (index > 0 && index >= last - 3)
{
    last = index;
    index = host.LastIndexOf('.', last - 1);
}
var domain = host.Substring(index + 1);

这将处理领域,如本地主机 example.com 的例子。 co.uk 。这不是最好的方法,但它至少可以节省您构筑的顶级域名一个巨大的列表。

This will handle domains such as localhost, example.com, and example.co.uk. It's not the best method, but at least it saves you from constructing a giant list of top-level domains.

这篇关于获得在C#/。NET的URL域名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆