How to get sub domain from url using C#


Simple method to get sub domain from url.

/// <summary>
/// Gets the sub domain.
/// </summary>
/// <param name="url">
/// The URL to get the sub domain from.
/// </param>
/// <returns>
/// The sub domain.
/// </returns>
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;
}