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(".")
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
如果路径以正斜杠 (/
) 或反斜杠 (\
) 开头,MapPath()
返回一个虚拟路径。
如果路径不以斜杠开头,则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
工作示例,希望这可以帮助展示使用MapPath的方法,不仅限于“/”。我们结合使用了“/”和“~”。
HostingEnvironment.MapPath
,因为它不需要HttpContext
:https://dev59.com/eXNA5IYBdhLWcg3wfN2O - skolima