This question already has an answer here:
- Top level domain from URL in C# 8 answers
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?
You can do this to get just the last two segments of the host name:
Or this:
This method will find include at least two domain name parts, but will also include intermediate parts of two characters or less:
This will handle domains such as
localhost
,example.com
, andexample.co.uk
. It's not the best method, but at least it saves you from constructing a giant list of top-level domains.Try regular expression?
You can try this. This can handle many kind of root domain if you define it in an array.