【发布时间】:2010-09-05 09:55:44
【问题描述】:
如果我已设法使用 Server.MapPath 找到并验证文件是否存在,并且我现在想将用户直接发送到该文件,那么转换该绝对路径的最快方法是什么回到相对网络路径?
【问题讨论】:
标签: c# asp.net .net path mappath
如果我已设法使用 Server.MapPath 找到并验证文件是否存在,并且我现在想将用户直接发送到该文件,那么转换该绝对路径的最快方法是什么回到相对网络路径?
【问题讨论】:
标签: c# asp.net .net path mappath
对于 asp.net 核心,我编写了辅助类来获取两个方向的路径。
public class FilePathHelper
{
private readonly IHostingEnvironment _env;
public FilePathHelper(IHostingEnvironment env)
{
_env = env;
}
public string GetVirtualPath(string physicalPath)
{
if (physicalPath == null) throw new ArgumentException("physicalPath is null");
if (!File.Exists(physicalPath)) throw new FileNotFoundException(physicalPath + " doesn't exists");
var lastWord = _env.WebRootPath.Split("\\").Last();
int relativePathIndex = physicalPath.IndexOf(lastWord) + lastWord.Length;
var relativePath = physicalPath.Substring(relativePathIndex);
return $"/{ relativePath.TrimStart('\\').Replace('\\', '/')}";
}
public string GetPhysicalPath(string relativepath)
{
if (relativepath == null) throw new ArgumentException("relativepath is null");
var fileInfo = _env.WebRootFileProvider.GetFileInfo(relativepath);
if (fileInfo.Exists) return fileInfo.PhysicalPath;
else throw new FileNotFoundException("file doesn't exists");
}
从 Controller 或服务注入 FilePathHelper 并使用:
var physicalPath = _fp.GetPhysicalPath("/img/banners/abro.png");
反之亦然
var virtualPath = _fp.GetVirtualPath(physicalPath);
【讨论】:
也许这可行:
String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
我用的是c#,但是可以适应vb。
【讨论】:
我知道这很旧,但我需要考虑虚拟目录(根据 @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.");
}
【讨论】:
我喜欢 Canoas 的想法。不幸的是,我没有可用的“HttpContext.Current.Request”(BundleConfig.cs)。
我改变了这样的方法:
public static string RelativePath(this HttpServerUtility srv, string path)
{
return path.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\", "/");
}
【讨论】:
拥有Server.RelativePath(path)不是很好吗?
好吧,你只需要扩展它;-)
public static class ExtensionMethods
{
public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)
{
return path.Replace(context.ServerVariables["APPL_PHYSICAL_PATH"], "~/").Replace(@"\", "/");
}
}
有了这个,你可以简单地调用
Server.RelativePath(path, Request);
【讨论】:
如果您使用了 Server.MapPath,那么您应该已经有了相对 Web 路径。根据MSDN documentation,该方法采用一个变量path,它是Web 服务器的虚拟路径。因此,如果您能够调用该方法,您应该已经可以立即访问相对 Web 路径。
【讨论】:
IEnumerable<FileInfo> 集合。在我的 Web 应用程序中,我可以提供此路径,将我的相对路径解析为物理路径,但是当我返回此递归列表并希望将它们映射回我的应用程序中的相对路径时,我没有该信息。