如果我们设法查找和检验是否存在一个文件使用的服务器。MapPath和我现在想要发送用户直接到那个文件是什么 最快的 的方式来转换,绝对路径返回成一个相对的网路径?

有帮助吗?

解决方案

也许这就可能的工作:

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

我使用的c#但可以适用于vb。

其他提示

不是很好有 服务器。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);

我知道这是旧的,但我需要账户的虚拟目录(每@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.电流。请求"提供(BundleConfig.cs)。

我改变了methode这样的:

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

如果您使用的服务器。MapPath,然后你应该已经有了相对的网路径。根据 MSDN文件, 这种方法需要一个变量, 路径, ,这是虚拟的路径的网络服务器。所以如果你能够呼吁的方法,你应该已经有了相对的网路径立即访问。

对于asp.net 核心我写的帮助类获得pathes在两个方向。

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");
    }

从控制器或服务的注射FilePathHelper和使用:

var physicalPath = _fp.GetPhysicalPath("/img/banners/abro.png");

和之亦然

var virtualPath = _fp.GetVirtualPath(physicalPath);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top