Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

uri

c#-2.0

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?

like image 606
Computer User Avatar asked May 10 '13 01:05

Computer User


1 Answers

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.

like image 81
p.s.w.g Avatar answered Oct 03 '22 04:10

p.s.w.g