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

后端 未结 10 706
失恋的感觉
失恋的感觉 2021-02-04 01:29

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/.

相关标签:
10条回答
  • 2021-02-04 02:02

    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.

    0 讨论(0)
  • 2021-02-04 02:03

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

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

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

    0 讨论(0)
  • 2021-02-04 02:07

    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.

    0 讨论(0)
  • 2021-02-04 02:14

    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.

    0 讨论(0)
  • 2021-02-04 02:17

    Did you try this? Seems simple enough.

    Uri parent = new Uri(uri, "..");
    
    0 讨论(0)
  • 2021-02-04 02:23

    Quick and dirty

    int pos = uriString.LastIndexOf('/');
    if (pos > 0) { uriString = uriString.Substring(0, pos); } 
    
    0 讨论(0)
提交回复
热议问题