【问题标题】:Get domain name of a url in C# / .NET [duplicate]在 C# / .NET 中获取 url 的域名 [重复]
【发布时间】:2013-05-04 15:23:02
【问题描述】:

代码:

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

给我“subdomain.website.com”

但我需要主域“website.com”作为任何 url 或 web 链接。

我该怎么做?

【问题讨论】:

  • 其实你想要顶级域名。 subdomain.website.com 是域,website.com 是顶级域。
  • 这确实不是一个很难解析的字符串。你试过.Splitstring.Join的简单组合吗?
  • @ysrb ,顶级域是 com,而不是 website.com。

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


【解决方案1】:

您可以这样做来获取主机名的最后两个部分:

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 等域。这不是最好的方法,但至少可以避免构建庞大的顶级域列表。

【讨论】:

  • 我认为第二种解决方案无法正常工作。 而且我认为我们还应该考虑一些 URL,例如 www.google.co.uk,其中根域名包含多个“.”
  • @imJustice 谢谢,我修复了第二个解决方案。我还添加了一个相当粗略的解决方案来处理多部分 TLD。
  • 如果域的倒数第二部分(如t.co 中的tgoo.gl 中的goo)小于3 个字符,则第三种方法将引发Index was out of range 异常。请解决这个问题,我将此代码用作扩展方法。
  • @harsh 查看我的更新。它会将example.t.co 视为根级名称(这可能不是您想要的),但至少不会在t.co 上引发异常。
【解决方案2】:

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

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

【讨论】:

  • @p.s.w.g 你是对的,改用 EndsWith。
  • +1 这也是一个很好的解决方案。
【解决方案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);
}

【讨论】:

  • 最好将正则表达式视为一门外语(对读者而言),并解释您的模式为何能解决问题。
猜你喜欢
  • 2017-12-14
  • 2014-05-31
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多