Search code examples
c#url

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


Given a URL as follows:

foo.bar.car.com.au

I need to extract foo.bar.

I came across the following code :

private static string GetSubDomain(Uri url)
{
    if (url.HostNameType == UriHostNameType.Dns)
    {
        string host = url.Host;
        if (host.Split('.').Length > 2)
        {
            int lastIndex = host.LastIndexOf(".");
            int index = host.LastIndexOf(".", lastIndex - 1);
            return host.Substring(0, index);
        }
    }         
    return null;     
}

This gives me like foo.bar.car. I want foo.bar. Should i just use split and take 0 and 1?

But then there is possible wwww.

Is there an easy way for this?


Solution

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