Given an absolute URI/URL, I want to get a URI/URL which doesn't contain the leaf portion. For example: given http://foo.com/bar/baz.html, I should get http://foo.com/bar/.
The code which I could come up with seems a bit lengthy, so I'm wondering if there is a better way.
static string GetParentUriString(Uri uri)
{
StringBuilder parentName = new StringBuilder();
// Append the scheme: http, ftp etc.
parentName.Append(uri.Scheme);
// Appned the '://' after the http, ftp etc.
parentName.Append("://");
// Append the host name www.foo.com
parentName.Append(uri.Host);
// Append each segment except the last one. The last one is the
// leaf and we will ignore it.
for (int i = 0; i < uri.Segments.Length - 1; i++)
{
parentName.Append(uri.Segments[i]);
}
return parentName.ToString();
}
One would use the function something like this:
static void Main(string[] args)
{
Uri uri = new Uri("http://foo.com/bar/baz.html");
// Should return http://foo.com/bar/
string parentName = GetParentUriString(uri);
}
Thanks, Rohit
There must be an easier way to do this with the built in uri methods but here is my twist on @unknown (yahoo)'s suggestion.
In this version you don't need
System.Linq
and it also handles URIs with query strings:Shortest way I found:
Did you try this? Seems simple enough.
I read many answers here but didn't find one that I liked because they break in some cases.
So, I am using this:
Note: It removes the Query and the Fragment intentionally.
Quick and dirty
PapyRef's answer is incorrect,
UriPartial.Path
includes the filename.seems to be cleanest/simplest implementation of the function requested.