在ASP.Net应用程序中执行Server.MapPath反向操作的最有效方法是什么 [英] What is the most efficient way to perform the reverse of Server.MapPath in an ASP.Net Application

查看:48
本文介绍了在ASP.Net应用程序中执行Server.MapPath反向操作的最有效方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个MVC应用程序,在该应用程序中,我正在从文件系统中读取文件列表,并且希望将该文件的相对URL传递给视图,最好以〜/"为前缀,以便选择任何视图cab会适当地呈现URL.

I am building an MVC application in which I am reading a list of files from the file system and I want to pass the relative URL to that file to the view, preferably prefixed with "~/" so that whatever view is selected cab render the URL appropriately.

为此,我需要枚举文件系统中的文件并将其物理路径转换回相对URL.我尝试了几种算法,但是我担心效率和最少的字符串操作.另外,我相信.Net Framework中没有可以执行此操作的东西,但是最新的MVC版本中有什么可以做到的吗?

To do this, I need to enumerate the files in the file system and convert their physical paths back to relative URLs. There are a few algorithms I've experimented with, but I am concerned about efficiency and minimal string operations. Also, I believe there's nothing in the .Net Framework that can perform this operation, but is there something in the latest MVC release that can?

推荐答案

目前,我不知道任何内置方法可以执行此操作,但这并不困难,我可以这样做:

At the moment I don't know any built-in method to do it, but it's not difficult, I do it like this:

  • 我们需要获取Application根目录,并在新路径中将其替换为~
  • 我们需要将反斜杠转换为斜杠
public string ReverseMapPath(string path)
{
    string appPath = HttpContext.Current.Server.MapPath("~");
    string res = string.Format("~{0}", path.Replace(appPath, "").Replace("\\", "/"));
    return res;
}

这篇关于在ASP.Net应用程序中执行Server.MapPath反向操作的最有效方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆