谁能解释Server.MapPath(".")
,Server.MapPath("~")
和之间Server.MapPath(@"\")
的区别Server.MapPath("/")
?
3 回答
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("")
产生这种效果。
只是为了稍微扩展@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)
or MapPath("")
,你实际上是在打电话MapPath(".")
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