2013-05-10 45 views
13

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

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

给我 “subdomain.website.com”

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

我该怎么做?

+2

到http://stackoverflow.com/questions/4643227/top-level-domain-from-url-in-c-sharp – ysrb 2013-05-10 01:35:17

+0

类似其实你想要的顶级域名。 subdomain.website.com是域名,website.com是顶级域名。 – ysrb 2013-05-10 01:35:54

+0

这真的不是一个很难解析的字符串。你是否尝试过'.Split'和'string.Join'的简单组合? – 2013-05-10 01:48:54

回答

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

这将处理域名,如localhost,example.comexample.co.uk。这不是最好的方法,但至少可以让您免于构建一个巨大的顶级域名列表。

+0

我认为第二个解决方案无法正常工作。 **我认为我们还应该考虑一些网址,例如www.google.co.uk根域名包含多个'。'** – 2power10 2013-05-10 07:00:27

+2

@imJustice谢谢,我修复了第二个解决方案。我还添加了一个相当简单的解决方案来处理多部分顶级域名。 – 2013-05-10 07:36:27

+0

如果域的后半部分(如't.co'中的't'和'goo.gl'中的'goo')小于3个字符,则第三种方法会抛出'索引超出范围'异常。请修复此问题,我将此代码用作扩展方法。 – shashwat 2013-06-24 18:38:55

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

最好将正则表达式作为外语处理(给读者)并解释为什么你的模式能够解决这个问题。 – 2013-05-10 02:00:14

+2

如果它是.org怎么办? – as9876 2015-11-08 20:06:38

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

@ p.s.w.g您说得对,改为使用EndsWith。 – 2power10 2013-05-10 07:45:33

+0

+1这是一个很好的解决方案。 – 2013-05-10 07:49:35