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

后端 未结 10 713
失恋的感觉
失恋的感觉 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: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.

提交回复
热议问题