絶対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