如何解决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
并在
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# 中,@
是逐字字面字符串运算符,表示字符串应该“按原样”使用,而不是为转义序列处理。
脚注
-
Server.MapPath(null)
也会Server.MapPath("")
产生这种效果。 -
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)
or MapPath("")
,你实际上是在打电话MapPath(".")
解决方法
谁能解释Server.MapPath(".")
,Server.MapPath("~")
和之间Server.MapPath(@"\")
的区别Server.MapPath("/")
?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。