C# Example to get SubDomain From URL


C# utility function to find sub domain name from URL. Make Uri object from string url and call below method.

Example

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

    return null;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.