Recently, I come across a simple problem where we have to extract subdomain from different URL. Then I decided to write simple extensions in “C# Subdomain from URL”, which can be used easily across the system.
Sharing the code:
public enum GetSubDomainEnum { ExcludeWWW, IncludeWWW };
public static class Extentions { public static string GetSubDomain(this Uri uri, GetSubDomainEnum getSubDomainOption = GetSubDomainEnum.IncludeWWW) { var subdomain = new StringBuilder(); for (var i = 0; i < uri.Host.Split(new char[]{'.'}).Length - 2; i++) { if(getSubDomainOption == GetSubDomainEnum.ExcludeWWW && uri.Host.Split(new char[]{'.'})[i].ToLowerInvariant() == "www") continue; subdomain.Append((i < uri.Host.Split(new char[]{'.'}).Length - 3 && uri.Host.Split(new char[]{'.'})[i+1].ToLowerInvariant() != "www") ? uri.Host.Split(new char[]{'.'})[i] + "." : uri.Host.Split(new char[]{'.'})[i]); } return subdomain.ToString(); } }
USAGE:
var subDomain = Request.Url.GetSubDomain(GetSubDomainOption.ExcludeWWW);
No Comments
Leave a comment Cancel