Dado un URI/URL absoluto, quiero obtener un URI/URL que no contenga la parte de la hoja. Por ejemplo: dado http://foo.com/bar/baz.html, debería obtener http://foo.com/bar/.Obteniendo el nombre principal de un URI/URL del nombre absoluto C#
El código que podría aparecer parece un poco largo, entonces me pregunto si hay una mejor manera.
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();
}
Se podría utilizar la función de algo como esto:
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);
}
Gracias, Rohit
Sí, pero esto no causará problemas si la URL tiene cadenas repetitivas: http://foo.com/bar/baz/bar – Rohit
¡Buen punto! Acabo de actualizar mi respuesta. ¡Gracias! – Martin
Advertencia: Esto ignora la cadena de consulta. – Brian