Extract domain name from URL

Shows three different methods how to extract the domain name of a given web adress.
/* ** Method 1 (using the build-in Uri-object) */ public static string ExtractDomainNameFromURL_Method1(string Url) { if (!Url.Contains("://")) Url = "http://" + Url; return new Uri(Url).Host; } /* ** Method 2 (using string modifiers) */ public static string ExtractDomainNameFromURL_Method2(string Url) { if (Url.Contains(@"://")) Url = Url.Split(new string[] { "://" }, 2, StringSplitOptions.None)[1]; return Url.Split('/')[0]; } /* ** Method 3 (using regular expressions -> slowest) */ public static string ExtractDomainNameFromURL_Method3(string Url) { return System.Text.RegularExpressions.Regex.Replace( Url, @"^([a-zA-Z]+:\/\/)?([^\/]+)\/.*?$", "$2" ); } //Example: string[] Urls = new string[] { "http://www.jonasjohn.de/snippets/csharp/", "www.jonasjohn.de/snippets/csharp/", "http://www.jonasjohn.de/", "ftp://www.jonasjohn.de/", "www.jonasjohn.de/", "https://subdomain.abc.def.jonasjohn.de/test.htm" }; // Test all urls with all different methods: foreach (string Url in Urls){ Console.WriteLine("Method 1: {0}", ExtractDomainNameFromURL_Method1(Url)); Console.WriteLine("Method 2: {0}", ExtractDomainNameFromURL_Method2(Url)); Console.WriteLine("Method 3: {0}", ExtractDomainNameFromURL_Method3(Url)); }

Url: http://www.jonasjohn.de/snippets/csharp/extract-domain-name-from-url.htm

Language: C# | User: ShareMySnippets | Created: Oct 16, 2013