Use C # to get the domain name through the URL

Source: Internet
Author: User

Recently, when you write a gadget, you need to get the domain name through the URL, do not know how the URI only get the method of host name and did not get the domain name method, so only to realize one, but I feel this method is more abnormal, I hope to come out and discuss with you, to see if there is a better way?

For example: http://www.google.co.uk, should return google.co.uk,http://www.test.googlepages.com, should return googlepages.com

My program is as follows, take out the discussion, write more mentally retarded, must know all the domain name suffix in advance.

Please tell me the good way:

private 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", ". is", ". 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 = Onebere Placedstr + "";
if (host.     IndexOf (BEREPLACEDSTR)!=-1)
{
      Host = host. Replace (Bereplacedstr, String. Empty);
break;
}
}

int dotindex = host. LastIndexOf ("."); The
host = URI. Host.substring (Dotindex + 1);
return host;
}

Thank you, sir!

Http://www.cnblogs.com/csharphack/archive/2006/09/26/get_domain_from_url.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.