从绝对名称C#获取URI/URL的父名称

Roh*_*hit 19 c# uri

给定一个绝对的URI/URL,我想得到一个不包含叶子部分的URI/URL.例如:给http://foo.com/bar/baz.html,我应该http://foo.com/bar/.

我能提出的代码似乎有点冗长,所以我想知道是否有更好的方法.

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();
    }
Run Code Online (Sandbox Code Playgroud)

一个人会使用这样的函数:

  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);                        
    }
Run Code Online (Sandbox Code Playgroud)

谢谢,罗希特

小智 32

你试过这个吗?看起来很简单.

Uri parent = new Uri(uri, "..");
Run Code Online (Sandbox Code Playgroud)

  • 略有不正确.正如你现在所做的那样,只有当uri是一个目录时它才是正确的.如果uri是一个文件(如原帖中所示),那么正确的方法是`Uri parent = new Uri(uri,".");` (20认同)

Mar*_*tin 29

这是我能想到的最短的:

static string GetParentUriString(Uri uri)
{
    return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length);
}
Run Code Online (Sandbox Code Playgroud)

如果要使用Last()方法,则必须包含System.Linq.


eft*_*eft 7

使用内置的uri方法必须有一个更简单的方法来做到这一点,但这是我对@unknown(雅虎)的建议的转折.
在此版本中您不需要System.Linq它,它还处理带有查询字符串的URI:

private static string GetParentUriString(Uri uri)
{
    return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments[uri.Segments.Length -1].Length - uri.Query.Length);
}
Run Code Online (Sandbox Code Playgroud)