C# 获取*(一级)域名方法

时间:2023-03-09 22:22:19
C# 获取*(一级)域名方法
   /// <summary>
/// 获取域名的*域名
/// </summary>
/// <param name="domain"></param>
/// <returns></returns>
public static string GetTopDomainName(string domain)
{
//https://www.safsd.asdfasdf.baidu.com.cn/ssssd/s/b/d/hhh.html?domain=sfsdf.com.cn&id=1
domain = domain.Trim().ToLower();
string rootDomain = ".com.cn|.gov.cn|.cn|.com|.net|.org|.so|.co|.mobi|.tel|.biz|.info|.name|.me|.cc|.tv|.asiz|.hk";
if (domain.StartsWith("http://")) domain = domain.Replace("http://", "");
if (domain.StartsWith("https://")) domain = domain.Replace("https://", "");
if (domain.StartsWith("www.")) domain = domain.Replace("www.", "");
//safsd.asdfasdf.baidu.com.cn/ssssd/s/b/d/hhh.html?domain=sfsdf.com.cn&id=1
if (domain.IndexOf("/") > )
domain = domain.Substring(, domain.IndexOf("/"));
//safsd.asdfasdf.baidu.com.cn
foreach (string item in rootDomain.Split('|'))
{
if (domain.EndsWith(item))
{
domain = domain.Replace(item, "");
if (domain.LastIndexOf(".") > )//adfasd.asdfas.cn
{
domain = domain.Replace(domain.Substring(, domain.LastIndexOf(".") + ), "");
}
return domain + item;
}
continue;
}
return "";
}