Biorąc pod uwagę bezwzględny adres URI/URL, chcę uzyskać identyfikator URI/URL, który nie zawiera części liści. Na przykład: podając http://foo.com/bar/baz.html, powinienem otrzymać http://foo.com/bar/.Uzyskiwanie nazwy nadrzędnej identyfikatora URI/adresu URL od nazwy absolutnej C#
Kod, który mogłem wymyślić wydaje się nieco długi, więc zastanawiam się, czy istnieje lepszy sposób.
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();
}
Można by użyć funkcji coś takiego:
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);
}
Dzięki Rohit
Tak, ale nie spowoduje to problemu, jeśli URL będzie zawierał ciągi: http://foo.com/bar/baz/bar – Rohit
Dobra rada! Właśnie zaktualizowałem swoją odpowiedź. Dzięki! – Martin
Ostrzeżenie: To ignoruje ciąg zapytania. – Brian