Another variant, without dependencies:
string GetDomainPart(string url)
{
var doubleSlashesIndex = url.IndexOf("://");
var start = doubleSlashesIndex != -1 ? doubleSlashesIndex + "://".Length : 0;
var end = url.IndexOf("/", start);
if (end == -1)
end = url.Length;
string trimmed = url.Substring(start, end - start);
if (trimmed.StartsWith("www."))
trimmed = trimmed.Substring("www.".Length );
return trimmed;
}
Examples:
http://www.google.com → google.com
http://www.google.co.uk/path1/path2 → google.co.uk
http://localhost.intranet:88/path1/path2 → localhost.intranet:88
http://www2.google.com → www2.google.com
new Uri("http://www.google.com").GetLeftPart(UriPartial.Authority).Replace("http://", "") ≡ "www.google.com"
– Lietuva