给定一个绝对 URI/URL,我想获取一个不包含叶部分的 URI/URL。例如:给定http://foo.com/bar/baz.html http://foo.com/bar/baz.html,我应该得到http://foo.com/bar/ 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();
}
人们会使用这样的函数:
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);
}
谢谢,
罗希特
你尝试过这个吗?看起来很简单。
Uri parent = new Uri(uri, "..");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)