Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Did you try this? Seems simple enough.

Uri parent = new Uri(uri, "..");

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);
}

Quick and dirty

int pos = uriString.LastIndexOf('/');
if (pos > 0) { uriString = uriString.Substring(0, pos); } 

Shortest way I found:

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

I read many answers here but didn't find one that I liked because they break in some cases.

So, I am using this:

public Uri GetParentUri(Uri uri) {
    var withoutQuery = new Uri(uri.GetComponents(UriComponents.Scheme |
                                                 UriComponents.UserInfo |
                                                 UriComponents.Host |
                                                 UriComponents.Port |
                                                 UriComponents.Path, UriFormat.UriEscaped));
    var trimmed = new Uri(withoutQuery.AbsoluteUri.TrimEnd('/'));
    var result = new Uri(trimmed, ".");
    return result;
}

Note: It removes the Query and the Fragment intentionally.

new Uri(uri.AbsoluteUri + "/../")

Get segmenation of url

url="http://localhost:9572/School/Common/Admin/Default.aspx"

Dim name() As String = HttpContext.Current.Request.Url.Segments

now simply using for loop or by index, get parent directory name

code = name(2).Remove(name(2).IndexOf("/"))

This returns me, "Common"

PapyRef's answer is incorrect, UriPartial.Path includes the filename.

new Uri(uri, ".").ToString()

seems to be cleanest/simplest implementation of the function requested.

Thought I'd chime in; despite it being almost 10 years, with the advent of the cloud, getting the parent Uri is a fairly common (and IMO more valuable) scenario, so combining some of the answers here you would simply use (extended) Uri semantics:

public static Uri Parent(this Uri uri)
{
    return new Uri(uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length - uri.Query.Length).TrimEnd('/'));
}

var source = new Uri("https://foo.azure.com/bar/source/baz.html?q=1");

var parent = source.Parent();         // https://foo.azure.com/bar/source
var folder = parent.Segments.Last();  // source

I can't say I've tested every scenario, so caution advised.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top