Reputation: 3942
string url = "www.google.com/?filter=xpto";
string domain = url.Contains('?')
? url.Substring(0, url.IndexOf('?'));
: url;
Is there a simpler way to do this w/o having to override Substring method?
Upvotes: 0
Views: 137
Reputation: 460228
You should also not use string methods if you work with Uri
s. Since your uri is somewhat malformed(f.e. it doesn't contain the protocol) it's a little bit more difficult to extract the domain:
string url = "www.google.com/?filter=xpto";
if (!url.Contains("://")) url = "http://" + url; // presume HTTP
string domain = url;
string host = url;
Uri uri;
if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri))
{
domain = uri.GetLeftPart(UriPartial.Authority); // http://www.google.com
host = uri.Host; // www.google.com, without protocol or port
}
Upvotes: 1
Reputation: 101701
Why don't you use Uri class instead ?
var url = new Uri("http://www.google.com/?filter=xpto");
var domain = url.Host;
Console.WriteLine(domain);
Upvotes: 0
Reputation:
You can write own extension method:
public static string GetDomain(this string url)
{
return url.Contains('?')
? url.Substring(0, url.IndexOf('?'));
: url;
}
Usage:
string domain = url.GetDomain();
Upvotes: 2