Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to parse the domain name from a string. The string can vary and I need the exact domain.

Examples of Strings:

http://somename.de/
www.somename.de/
somename.de/
somename.de/somesubdirectory
www.somename.de/?pe=12

I need it in the following format with just the domain name, the tld, and the www, if applicable:

www.somename.de

How do I do that using C#?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
362 views
Welcome To Ask or Share your Answers For Others

1 Answer

As an alternative to a regex solution, you can let the System.Uri class parse the string for you. You just have to make sure the string contains a scheme.

string uriString = "http://www.google.com/search";

if (!uriString.Contains(Uri.SchemeDelimiter))
{
    uriString = string.Concat(Uri.UriSchemeHttp, Uri.SchemeDelimiter, uriString);
}

string domain = new Uri(uriString).Host;

This solution also filters out any port numbers and converts IPv6 addresses to its canonical form.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...