How do I check for a URL's top-level domain in ASP.NET/C#?
if (Request.Url.Host.ToLower().EndsWith(".fr"))
{
...
}
Get domain name of a url in C# / .NET
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.
easy way to get the top level domain?
It's called a toplevel domain (tld) but for the BBC that's just "uk", not "co.uk".
What you want does not follow a standard so you'll need a table to check 'potential' pseudo-tld's
Related Topics
Set Environment Variables for a Process
System.Io.Filestream Fileaccess VS Fileshare
Efficient Way to Round Double Precision Numbers to a Lower Precision Given in Number of Bits
Multiple Identities in ASP.NET Core 2.0
How to Call a SQL Stored Procedure Using Entityframework 7 and ASP.NET 5
How to Know the Repeating Decimal in a Fraction
Very Simple Definition of Initializecomponent(); Method
How to Simply 'Read' a File That Is in Use
Set Item Focus in Listview Wpf
Accuracy of Textrenderer.Measuretext Results
Creating a Circularly Linked List in C#
Outofmemoryexception on Declaration of Large Array
How to Find the Position of a Cursor in a Text Box? C#
Ef4 Cause Circular Reference in Web Service
Using System.Io.Packaging to Generate a Zip File
Get the Application Pool Identity Programmatically
Draw Multiple Freehand Polyline or Curve Drawing - Adding Undo Feature