首页 新闻 会员 周边

如何从地址字符串中获取主域名

0
悬赏园豆:50 [已关闭问题] 关闭于 2011-10-18 12:06

如字符串为:

string a="http://www.cnblogs.com";
string b="http://q.cnblogs.com";
string c="http://bbs.youa.baidu.com/"

我知道可以用Uri得到地址的域名:

Uri a=new Uri(a);
Uri b=new Uri(b);
Uri c=new Uri(c);
string ahost=a.Host;//www.cnblogs.com
string bhost=b.Host;//q.cnblogs.com
string chost=c.Host;//bbs.youa.baidu.com

我现在想得到主域名,也就是说我想得到的结果是:

cnblogs.com
cnblogs.com
baidu.com

请高手指点。

artwl的主页 artwl | 专家六级 | 园豆:16736
提问于:2011-10-18 11:50
< >
分享
所有回答(1)
0

自己解决了:

public static string GetDomain(string url)
{
string host;
Uri uri;
try
{
uri = new Uri(url);
host = uri.Host + "";
}
catch
{
return "";
}

string[] BeReplacedStrs = new string[] { ".com.cn", ".edu.cn", ".net.cn", ".org.cn", ".co.jp", ".gov.cn", ".co.uk", ".ac.cn", ".edu", ".tv", ".info", ".com", ".ac", ".ag", ".am", ".at", ".be", ".biz", ".bz", ".cc", ".cn", ".com", ".de", ".es", ".eu", ".fm", ".gs", ".hk", ".in", ".info", ".io", ".it", ".jp", ".la", ".md", ".ms", ".name", ".net", ".nl", ".nu", ".org", ".pl", ".ru", ".sc", ".se", ".sg", ".sh", ".tc", ".tk", ".tv", ".tw", ".us", ".co", ".uk", ".vc", ".vg", ".ws", ".il", ".li", ".nz" };

foreach (string oneBeReplacedStr in BeReplacedStrs)
{
string BeReplacedStr = oneBeReplacedStr + "";
if (host.IndexOf(BeReplacedStr) != -1)
{
host = host.Replace(BeReplacedStr, string.Empty);
break;
}
}

int dotIndex = host.LastIndexOf(".");
host = uri.Host.Substring(dotIndex + 1);
return host;
}
artwl | 园豆:16736 (专家六级) | 2011-10-18 12:06
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册