Get specific subdomain from URL in foo.bar.car.com

后端 未结 7 1759
清酒与你
清酒与你 2020-11-30 10:19

Given a URL as follows:

foo.bar.car.com.au

I need to extract foo.bar.

I came across the following code :

pr         


        
7条回答
  •  离开以前
    2020-11-30 10:42

    Given your requirement (you want the 1st two levels, not including 'www.') I'd approach it something like this:

    private static string GetSubDomain(Uri url)
    {
    
        if (url.HostNameType == UriHostNameType.Dns)
        {
    
            string host = url.Host;
    
            var nodes = host.Split('.');
            int startNode = 0;
            if(nodes[0] == "www") startNode = 1;
    
            return string.Format("{0}.{1}", nodes[startNode], nodes[startNode + 1]);
    
        }
    
        return null; 
    }
    

提交回复
热议问题