Home > Enterprise >  Method for comparing URLs with the same root
Method for comparing URLs with the same root

Time:08-26

I am looking into trying to compare 2 URLs in C# for equal root domains, I.E.

sub.example.com matches example.com and othersub.example.com.

I had a look into using the Uri class, but that will parse the full URL including the subdomains.

I had thought about splitting the string at each . and then comparing the last 2 last elements which would normally be the root domain name, however that causes issues as often the TLD can also have a subdomain I.E. example.com.au would then match other.com.au.

I guess I'm hoping if anyone knows a NuGet library that can take into account common top level domains (including multi part ones) and then compare the actual specified domain

CodePudding user response:

You can use Nager.PublicSuffix package.

Install via nuget:

PM> Install-Package Nager.PublicSuffix

Example:

var domainParser = new DomainParser(new WebTldRuleProvider());

var domainInfo = domainParser.Parse("sub.test.co.uk");
//domainInfo.Domain = "test";
//domainInfo.Hostname = "sub.test.co.uk";
//domainInfo.RegistrableDomain = "test.co.uk";
//domainInfo.SubDomain = "sub";
//domainInfo.TLD = "co.uk";

Then compare via the domainInfo.TLD

  • Related