Server.MapPath(“.”),Server.MapPath(~”,Server.MapPath(@“\”),Server.MapPath(“/”)。有什么区别?

有人能解释一下Server.MapPath(“.”Server.MapPath(“~”Server.MapPath(@“\”)和Server.MapPath(“/”)之间的区别吗

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

  • 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(“.”)返回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

如果路径以正斜杠(/)或反斜杠(\)开头,MapPath()将返回一个路径,就像路径是完整的虚拟路径一样

如果路径不是以斜杠开头,则MapPath()将返回相对于正在处理的请求目录的路径

注意:在C#中,@是逐字逐句的字符串运算符,这意味着字符串应按“原样”使用,而不是针对转义序列进行处理。

脚注

  1. Server.MapPath(null)Server.MapPath(“”)也会产生这种效果

发表评论