且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从任何 URL 获取确切的域名

更新时间:2023-02-25 15:17:50

您可以使用 Uri类访问一个URI的所有组件:

You can use the Uri Class to access all components of an URI:

var uri = new Uri("http://www.google.co.uk/path1/path2");

var host = uri.Host;

// host == "www.google.co.uk"

但是,没有内置的方法可以从www.google.co.uk"中去除子域www".您需要实现自己的逻辑,例如


However, there is no built-in way to strip the sub-domain "www" off "www.google.co.uk". You need to implement your own logic, e.g.

var parts = host.ToLowerInvariant().Split('.');

if (parts.Length >= 3 &&
    parts[parts.Length - 1] == "uk" &&
    parts[parts.Length - 2] == "co")
{
    var result = parts[parts.Length - 3] + ".co.uk";

    // result == "google.co.uk"
}