asp.net 服务器Map路径(“.”)、服务器Map路径(“~”)、服务器Map路径(@"\”)、服务器Map路径(“/”),有什么区别呢?

velaa5lx  于 2023-08-08  发布在  .NET
关注(0)|答案(4)|浏览(103)

有谁能解释一下Server.MapPath(".")Server.MapPath("~")Server.MapPath(@"\")Server.MapPath("/")之间的区别吗?

p4rjhz4m

p4rjhz4m1#

Server.MapPath指定要Map到物理目录的相对或虚拟路径。

  • Server.MapPath(".") 1返回文件的当前物理目录(例如aspx)正在执行
  • Server.MapPath("..")返回父目录
  • Server.MapPath("~")返回到应用程序根的物理路径
  • Server.MapPath("/")返回到域名根的物理路径(不一定与应用程序的根相同)
  • 示例:*

假设您将网站应用程序(http://www.example.com/)指向

C:\Inetpub\wwwroot

字符串
并将您的商店应用程序(子网站作为IIS中的虚拟目录,标记为应用程序)安装在

D:\WebApps\shop


例如,如果在以下请求中调用Server.MapPath()

http://www.example.com/shop/products/GetProduct.aspx?id=2342


然后:

  • Server.MapPath(".") 1返回D:\WebApps\shop\products
  • Server.MapPath("..")返回D:\WebApps\shop
  • Server.MapPath("~")返回D:\WebApps\shop
  • Server.MapPath("/")返回C:\Inetpub\wwwroot
  • Server.MapPath("/shop")返回D:\WebApps\shop

如果Path以正斜杠(/)或反斜杠(\)开头,则MapPath()将返回一个路径,就好像Path是一个完整的虚拟路径。
如果Path不是以斜杠开头,则MapPath()返回一个相对于正在处理的请求的目录的路径。

  • 注意:在C#中,@是逐字字符串操作符,这意味着字符串应该“按原样”使用,而不是进行转义序列处理。
  • 脚注 *
  1. Server.MapPath(null)Server.MapPath("")produce this effect too
nlejzf6q

nlejzf6q2#

只是为了扩展@splattne的回答:
MapPath(string virtualPath)调用以下代码:

public string MapPath(string virtualPath)
{
    return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));
}

字符串
MapPath(VirtualPath virtualPath)依次调用MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping),其中包含以下内容:

//...
if (virtualPath == null)
{
    virtualPath = VirtualPath.Create(".");
}
//...


因此,如果调用MapPath(null)MapPath(""),实际上就是调用MapPath(".")

vjhs03f7

vjhs03f73#

1)Server.MapPath(".")--返回文件的“当前物理目录”(例如aspx)正在执行。
例:假设D:\WebApplications\Collage\Departments
2)Server.MapPath("..")--返回“父目录”
例如D:\WebApplications\Collage
3)Server.MapPath("~")--返回“应用程序根目录的物理路径”
例如D:\WebApplications\Collage
4)Server.MapPath("/")--返回到域名根的物理路径
例如C:\Inetpub\wwwroot

cs7cruho

cs7cruho4#

工作示例,希望这有助于展示使用MapPath的方法,而不仅仅是一个“/”。我们正在组合“/”和“~”。

  1. string lotMapsUrl =“~/WebFS/Transport/Maps/Lots/";- 将长URL放入变量中
  2. string getMapsDir = Server.MapPath(getMapsUrl);- 获取到该位置的完整物理路径
  3. String[] files = Directory.GetFiles(lotMapsUrl);- 从物理路径获取文件列表。

相关问题