Development Desk

Just another WordPress.com site

Monthly Archives: January 2013

Get Domain Name without any Sub-domain name

Hi,

you can get domain name without any sub-domain by using below method

public string GetDom(HttpRequest Request)
{
          var fullDomain = new      Uri(Request.Url.Host.ToLower()).GetComponents(UriComponents.Host, UriFormat.SafeUnescaped);

        if (fullDomain.EndsWith(“.com”))
               return GetHostUrl(fullDomain, 2);
        else if (fullDomain.EndsWith(“.co.uk”))
               return GetHostUrl(fullDomain, 3);
        return fullDomain;
}

public string GetHostUrl(string hostUrl, int parameters)
{
         var domainParts = hostUrl
         .Split(‘.’) // [“test”, “example”, “co”,”uk”]
         .Reverse() // [“uk”,”co”, “example”, “test”]
         .Take(parameters) // [“uk”,”co” “example”]
         .Reverse(); // [“example”, “co”,”uk”]
          var domain = String.Join(“.”, domainParts);
          return domain;
}

These method can be made more generic.

Thanks

Advertisements