给定一个绝对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();
}
有人会像这样使用该函数:
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);
}
谢谢,Rohit
Uri parent = new Uri(uri, ".");
。 - Nick Babcock