绝对路径返回web相对路径

tag*_*s2k 64 .net c# asp.net mappath path

如果我已经设法使用Server.MapPath找到并验证文件的存在,并且我现在想要将用户直接发送到该文件,那么将该绝对路径转换回相对Web路径的最快方法是什么?

Gat*_*ler 55

也许这可能会奏效:

String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
Run Code Online (Sandbox Code Playgroud)

我正在使用c#但可以适应vb.

  • @ [GateKiller](http://stackoverflow.com/questions/3164?sort=oldest#3218):请注意,如果您在网站中使用IIS虚拟目录,则您的解决方案可能会失败,因为应用程序物理路径可能与文件的物理路径. (2认同)

Can*_*oas 37

使用Server.RelativePath(路径)不是很好吗?

好吧,你只需要扩展它;-)

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

有了它,你可以简单地打电话

Server.RelativePath(path, Request);
Run Code Online (Sandbox Code Playgroud)

  • 更好的物理路径替换是〜/.path.Replace(context.ServerVariables("APPL_PHYSICAL_PATH"),"〜/") (3认同)

Ale*_*use 13

我知道这是旧的,但我需要考虑虚拟目录(根据@Costo的评论).这似乎有助于:

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.");
}
Run Code Online (Sandbox Code Playgroud)


Pie*_*che 5

我喜欢卡诺阿斯的想法。不幸的是,我没有可用的“ HttpContext.Current.Request”(BundleConfig.cs)。

我这样改变了方法:

public static string RelativePath(this HttpServerUtility srv, string path)
{
     return path.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\", "/");
}
Run Code Online (Sandbox Code Playgroud)