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

代码:

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

给了我“subdomain.website.com”

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

我怎么做?

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

 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 。 这不是最好的方法,但至少它可以帮助您避免构建一个巨大的顶级域名列表。

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

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

试试正则表达式?

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