Get domain name of a url in C# / .NET

Computer User picture Computer User · May 10, 2013 · Viewed 25.9k times · Source

The code:

string sURL = "http://subdomain.website.com/index.htm";
MessageBox.Show(new System.Uri(sURL).Host);

gives me "subdomain.website.com"

But I need the main domain "website.com" for any url or web link.

How do I do that?

Answer

p.s.w.g picture p.s.w.g · May 10, 2013

You can do this to get just the last two segments of the host name:

string[] hostParts = new System.Uri(sURL).Host.Split('.');
string domain = String.Join(".", hostParts.Skip(Math.Max(0, hostParts.Length - 2)).Take(2));

Or this:

var host = new System.Uri(sURL).Host;
var domain = host.Substring(host.LastIndexOf('.', host.LastIndexOf('.') - 1) + 1);

This method will find include at least two domain name parts, but will also include intermediate parts of two characters or less:

var host = new System.Uri(sURL).Host;
int index = host.LastIndexOf('.'), last = 3;
while (index > 0 && index >= last - 3)
{
    last = index;
    index = host.LastIndexOf('.', last - 1);
}
var domain = host.Substring(index + 1);

This will handle domains such as localhost, example.com, and example.co.uk. It's not the best method, but at least it saves you from constructing a giant list of top-level domains.