谁能解释 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
并在
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)
或 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
HostingEnvironment.MapPath
,因为它不需要HttpContext
:stackoverflow.com/q/944219/3205