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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16473838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:05:24  来源:igfitidea点击:

Get domain name of a url in C# / .NET

c#.neturic#-2.0

提问by Computer User

The code:

编码:

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

gives me "subdomain.website.com"

给我“subdomain.website.com”

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

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

How do I do that?

我怎么做?

采纳答案by p.s.w.g

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

Or this:

或这个:

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

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.

这将处理领域,如localhostexample.comexample.co.uk。这不是最好的方法,但至少它使您免于构建庞大的顶级域列表。

回答by Marvin W

Try regular expression?

试试正则表达式?

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

回答by 2power10

You can try this. This can handle many kind of root domain if you define it in an array.

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

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