Dato un URI/URL assoluto, voglio ottenere un URI/URL che non contenga la parte foglia. Ad esempio: dato http://foo.com/bar/baz.html, dovrei ottenere http://foo.com/bar/.Ottenere il nome genitore di un URI/URL dal nome assoluto C#
Il codice che ho potuto ricavare sembra un po 'lungo, quindi mi chiedo se c'è un modo migliore.
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();
}
Si potrebbe utilizzare la funzione di qualcosa di simile a questo:
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);
}
Grazie, Rohit
Sì, ma questo non causerà problemi se l'URL ha ripetute stringhe: http://foo.com/bar/baz/bar – Rohit
Buon punto! Ho appena aggiornato la mia risposta. Grazie! – Martin
Attenzione: questo ignora la stringa di query. – Brian