Getting exact domain name from any URL [duplicate]
I need to extract the ex开发者_JAVA技巧act domain name from any Url.
For example,
Url : http://www.google.com --> Domain : google.com
Url : http://www.google.co.uk/path1/path2 --> Domain : google.co.uk
How can this is possible in c# ? Is there a complete TLD list or a parser for that task ?
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"
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"
}
Use:
new Uri("http://www.stackoverflow.com/questions/5984361/c-sharp-getting-exact-domain-name-from-any-url?s=45faab89-43eb-41dc-aa5b-8a93f2eaeb74#new-answer").GetLeftPart(UriPartial.Authority).Replace("/www.", "/").Replace("http://", ""));
Input:
http://www.stackoverflow.com/questions/5984361/c-sharp-getting-exact-domain-name-from-any-url?s=45faab89-43eb-41dc-aa5b-8a93f2eaeb74#new-answer
Output:
stackoverflow.com
Also works for the following.
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
Try the System.Uri class.
http://msdn.microsoft.com/en-us/library/system.uri.aspx
new Uri("http://www.google.co.uk/path1/path2").Host
which returns "www.google.co.uk". From there it's string manipulation. :/
use:
var uri =new Uri(Request.RawUrl); // to get the url from request or replace by your own
var domain = uri.GetLeftPart( UriPartial.Authority );
Input:
Url = http://google.com/?search=true&q=how+to+use+google
Result:
domain = google.com
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
精彩评论