给定一个绝对的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)
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.
使用内置的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)
归档时间: |
|
查看次数: |
22158 次 |
最近记录: |