Friday, May 27, 2011

Get the sub-domain from the provided URL

///Get the sub-domain from the provided URL
/// </summary>
/// <param name="url">URL to retrieve sub-domain from</param>
/// <returns></returns>
public string RetrieveSubDomain(Uri url)
{
string subDomain = "";
if (url.HostNameType == UriHostNameType.Dns && 
               (!(url.HostNameType ==
UriHostNameType.Unknown)))
{
string host = url.Host;
if (host.StartsWith("www."))
{
host = host.Remove(0, 4);
}

int length = host.Split('.').Length;if (length > 2)
{
int last = host.LastIndexOf(".");
int idx = host.LastIndexOf(".", last - 1);
subDomain = host.Substring(0, idx);
}
}
return subDomain;
}

protected void btnFindSubDomain_Click(object sender, EventArgs e)
{
string subdomain = RetrieveSubDomain(new Uri(txtUrl.Text));
Response.Write(subdomain);
}

No comments :

Post a Comment