tags:

views:

2038

answers:

4

Hello,

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

+4  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.

Martin
Yes, but won't this cause a problem if the URL has repeating strings: http://foo.com/bar/baz/bar
Rohit
Good point! I just updated my answer. Thanks!
Martin
A: 

Quick and dirty

int pos = uriString.LastIndexOf('/');
if (pos > 0) { uriString = uriString.Substring(0, pos); }
dbkk
just an FYI...there are instances where this can break...if there is an unencoded URI in the query string which is amazingly legal
Steve
Thank you Steve. To me, it proves the point that one should never use naked string or regex manipulation for complex formats such as URI or file path :)
dbkk
+1  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);
    }
eft
A: 

Shortest way I found:

static Uri GetParent(Uri uri) {
    return new Uri(uri, Path.GetDirectoryName(uri.LocalPath) + "/");
}
riel