如果我已经使用Server.MapPath设法找到并验证了文件的存在,并且现在想直接将用户发送到该文件,那么将绝对路径转换回相对Web路径的最快方法是什么?
也许这可能有效:
1
| String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty); |
我正在使用c#,但可以适应vb。
拥有Server.RelativePath(path)会不会很好?
好吧,您只需要扩展它即可;-)
1 2 3 4 5 6 7
| public static class ExtensionMethods
{
public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)
{
return path.Replace(context.ServerVariables["APPL_PHYSICAL_PATH"],"~/").Replace(@"","/");
}
} |
有了这个你可以简单地打电话
1
| Server.RelativePath(path, Request); |
我知道这很旧,但是我需要考虑虚拟目录(根据@Costo的评论)。这似乎有帮助:
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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.");
} |
我喜欢卡诺阿斯的想法。不幸的是,我没有可用的" HttpContext.Current.Request"(BundleConfig.cs)。
我这样改变了方法:
1 2 3 4
| public static string RelativePath(this HttpServerUtility srv, string path)
{
return path.Replace(HttpContext.Current.Server.MapPath("~/"),"~/").Replace(@"","/");
} |
如果使用Server.MapPath,则应该已经具有相对的Web路径。根据MSDN文档,此方法采用一个变量path,这是Web服务器的虚拟路径。因此,如果您能够调用该方法,则应该已经可以立即访问相关的Web路径。
对于asp.net核心,我编写了帮助程序类来获取双向路径。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| 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并使用:
1
| var physicalPath = _fp.GetPhysicalPath("/img/banners/abro.webp"); |
反之亦然
1
| var virtualPath = _fp.GetVirtualPath(physicalPath); |