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

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

提交回复
热议问题