Ruta absoluta de vuelta a la ruta relativa a la web


Si he conseguido localizar y verificar la existencia de un archivo utilizando Server.MapPath y ahora quiero enviar al usuario directamente a ese archivo, ¿cuál es la forma más rápida de convertir esa ruta absoluta en una ruta web relativa?

Author: Agnel Amodia, 2008-08-06

5 answers

Tal vez esto podría funcionar:

String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);

Estoy usando c# pero podría ser adaptado a vb.

 50
Author: GateKiller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-20 14:18:12

No sería bueno tener Servidor.relativePath (path) ?

Bueno, solo necesitas extenderlo; -)

public static class ExtensionMethods
{
    public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)
    {
        return path.Replace(context.ServerVariables["APPL_PHYSICAL_PATH"], "~/").Replace(@"\", "/");
    }
}

Con esto simplemente puedes llamar

Server.RelativePath(path, Request);
 35
Author: Canoas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-24 15:42:00

Sé que esto es viejo, pero necesitaba tener en cuenta los directorios virtuales (según el comentario de @Costo). Esto parece ayudar:

static string RelativeFromAbsolutePath(string path)
{
    if(HttpContext.Current != null)
    {
        var request = HttpContext.Current.Request;
        var applicationPath = request.PhysicalApplicationPath;
        var virtualDir = request.ApplicationPath;
        virtualDir = virtualDir == "/" ? virtualDir : (virtualDir + "/");
        return path.Replace(applicationPath, virtualDir).Replace(@"\", "/");
    }

    throw new InvalidOperationException("We can only map an absolute back to a relative path if an HttpContext is available.");
}
 12
Author: AlexCuse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-07 14:12:30

Me gusta la idea de Canoas. Desafortunadamente no tenía " HttpContext.Actual.Solicitar " disponible (BundleConfig.cs).

Cambié el método así:

public static string RelativePath(this HttpServerUtility srv, string path)
{
     return path.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\", "/");
}
 4
Author: Pierre Chavaroche,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-24 08:19:45

Si ha utilizado el servidor.MapPath, entonces ya debería tener la ruta web relativa. De acuerdo con la documentación MSDN, este método toma una variable, path, que es la ruta virtual del servidor Web. Por lo tanto, si pudo llamar al método, ya debería tener la ruta web relativa accesible inmediatamente.

 2
Author: Yaakov Ellis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-06 09:23:44