Getting the parent name of a URI/URL from absolute

2020-05-26 03:25发布

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

标签: c# uri
10条回答
爷的心禁止访问
2楼-- · 2020-05-26 03:50

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);
}
查看更多
再贱就再见
3楼-- · 2020-05-26 03:50

Shortest way I found:

static Uri GetParent(Uri uri) {
    return new Uri(uri, Path.GetDirectoryName(uri.LocalPath) + "/");
}
查看更多
放我归山
4楼-- · 2020-05-26 03:53

Did you try this? Seems simple enough.

Uri parent = new Uri(uri, "..");
查看更多
爷的心禁止访问
5楼-- · 2020-05-26 03:53

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.

查看更多
Fickle 薄情
6楼-- · 2020-05-26 03:54

Quick and dirty

int pos = uriString.LastIndexOf('/');
if (pos > 0) { uriString = uriString.Substring(0, pos); } 
查看更多
看我几分像从前
7楼-- · 2020-05-26 03:56

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

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

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

查看更多
登录 后发表回答