Sometimes it is useful to get the base URL of a given URL.
For some reason there is no built in function in the URI class to do that.
A simple implementation of a function to get the base URL from a given URI would be:
////////////////////////////////////////////////////////////////
// Extract a base URL from a URL
////////////////////////////////////////////////////////////////
public Uri extractBaseURLFromURL(Uri url)
{
return new Uri(url.Scheme.ToString() + "://" + url.Authority);
}
////////////////////////////////////////////////////////////////
As a usage example if we call extractBaseURLFromURL and supply the following URL
http://msdn2.microsoft.com/en-us/netframework/default.aspx
The function will return the following URL
http://msdn2.microsoft.com
----------
Update:
----------
Nick Berardi offered a more elegant solution by using the GetLeftPart function (see discussion below):
Example:
// extract a base url from a url
public static Uri extractBaseURLFromURL(Uri url)
{
return new Uri(url.GetLeftPart(UriPartial.Authority));
}