C# 返回到网络相对路径的绝对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Absolute path back to web-relative path
提问by tags2k
If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the fastestway to convert that absolute path back into a relative web path?
如果我已设法使用 Server.MapPath 找到并验证文件是否存在,并且我现在想将用户直接发送到该文件,那么将该绝对路径转换回相对 Web 路径的最快方法是什么?
采纳答案by GateKiller
Perhaps this might work:
也许这可能有效:
String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
I'm using c# but could be adapted to vb.
我正在使用 c# 但可以适应 vb。
回答by Yaakov Ellis
If you used Server.MapPath, then you should already have the relative web path. According to the MSDN documentation, this method takes one variable, path, which is the virtual path of the Web server. So if you were able to call the method, you should already have the relative web path immediately accessible.
如果您使用了 Server.MapPath,那么您应该已经有了相对的 Web 路径。根据MSDN 文档,此方法采用一个变量path,即 Web 服务器的虚拟路径。因此,如果您能够调用该方法,您应该已经可以立即访问相对 Web 路径。
回答by Canoas
Wouldn't it be nice to have Server.RelativePath(path)?
拥有Server.RelativePath(path)不是很好吗?
well, you just need to extend it ;-)
好吧,你只需要扩展它;-)
public static class ExtensionMethods
{
public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)
{
return path.Replace(context.ServerVariables["APPL_PHYSICAL_PATH"], "~/").Replace(@"\", "/");
}
}
With this you can simply call
有了这个,你可以简单地打电话
Server.RelativePath(path, Request);
回答by AlexCuse
I know this is old but I needed to account for virtual directories (per @Costo's comment). This seems to help:
我知道这很旧,但我需要考虑虚拟目录(根据@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.");
}
回答by Pierre Chavaroche
I like the idea from Canoas. Unfortunately I had not "HttpContext.Current.Request" available (BundleConfig.cs).
我喜欢 Canoas 的想法。不幸的是,我没有可用的“HttpContext.Current.Request”(BundleConfig.cs)。
I changed the methode like this:
我改变了这样的方法:
public static string RelativePath(this HttpServerUtility srv, string path)
{
return path.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\", "/");
}
回答by Lapenkov Vladimir
For asp.net core i wrote helper class to get pathes in both directions.
对于 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");
}
from Controller or service inject FilePathHelper and use:
从控制器或服务注入 FilePathHelper 并使用:
var physicalPath = _fp.GetPhysicalPath("/img/banners/abro.png");
and versa
反之亦然
var virtualPath = _fp.GetVirtualPath(physicalPath);