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

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

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

提交回复
热议问题