在C#/ .NET中获取URL的域名

时间:2013-05-10 01:33:30

标签: c# .net uri c#-2.0

代码:

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

给了我“subdomain.website.com”

但我需要主域名“website.com”用于任何网址或网站链接。

我该怎么做?

3 个答案:

答案 0 :(得分:15)

您可以执行此操作以获取主机名的最后两个部分:

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);

此方法将包含至少两个域名部分,但也包括两个或更少字符的中间部分:

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);

这将处理localhostexample.comexample.co.uk等域名。它不是最好的方法,但至少它可以帮助您避免构建一个巨大的顶级域名列表。

答案 1 :(得分:4)

你可以试试这个。如果您在数组中定义它,则可以处理多种根域。

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

string[] col = { ".com", ".cn", ".co.uk"/*all needed domain in lower case*/ };
foreach (string name in col)
{
    if (host.EndsWith(name))
    {
        int idx = host.IndexOf(name);
        int sec = host.Substring(0, idx - 1).LastIndexOf('.');
        var rootDomain = host.Substring(sec + 1);
    }
}

答案 2 :(得分:3)

尝试正则表达式?

using System.Text.RegularExpressions;

string sURL = "http://subdomain.website.com/index.htm";
string sPattern = @"\w+.com";

// Instantiate the regular expression object.
Regex r = new Regex(sPattern, RegexOptions.IgnoreCase);

// Match the regular expression pattern against a text string.
Match m = r.Match(sUrl);
if (m.Success)
{
    MessageBox.Show(m.Value);
}