Getting exact domain name from any URL

Yazginin Firati picture Yazginin Firati · May 12, 2011 · Viewed 38.1k times · Source

I need to extract the exact domain name from any Url.

For example,

Url : http://www.google.com --> Domain : google.com

Url : http://www.google.co.uk/path1/path2 --> Domain : google.co.uk

How can this is possible in c# ? Is there a complete TLD list or a parser for that task ?

Answer

dtb picture dtb · May 12, 2011

You can use the Uri Class to access all components of an URI:

var uri = new Uri("http://www.google.co.uk/path1/path2");

var host = uri.Host;

// host == "www.google.co.uk"

However, there is no built-in way to strip the sub-domain "www" off "www.google.co.uk". You need to implement your own logic, e.g.

var parts = host.ToLowerInvariant().Split('.');

if (parts.Length >= 3 &&
    parts[parts.Length - 1] == "uk" &&
    parts[parts.Length - 2] == "co")
{
    var result = parts[parts.Length - 3] + ".co.uk";

    // result == "google.co.uk"
}