Q:

Getting the parent name of a URI/URL from absolute name C#

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

A:

Did you try this?  Seems simple enough. 
Uri parent = new Uri(uri, "..");

A:

This is the shortest I can come up with: 
static string GetParentUriString(Uri uri)
{
    return uri. AbsoluteUri. Remove(uri. AbsoluteUri. Length - uri. Segments. Last().Length);
}

If you want to use the Last() method, you will have to include System. Linq. 

A:

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:
private static string GetParentUriString(Uri uri)
{
    return uri. AbsoluteUri. Remove(uri. AbsoluteUri. Length - uri. Segments[uri. Segments. Length -1].Length - uri. Query. Length);
}

