Man*_*anu 442 asp.net filesystems directory mapping path
任何人能解释的区别Server.MapPath("."),Server.MapPath("~"),Server.MapPath(@"\")和Server.MapPath("/")?
spl*_*tne 797
Server.MapPath指定映射到物理目录的相对路径或虚拟路径.
Server.MapPath(".")1返回正在执行的文件(例如aspx)的当前物理目录Server.MapPath("..") 返回父目录Server.MapPath("~") 返回应用程序根目录的物理路径Server.MapPath("/") 返回域名根目录的物理路径(不一定与应用程序的根目录相同)一个例子:
假设你指的是一个网站应用程序(http://www.example.com/)
C:\Inetpub\wwwroot
Run Code Online (Sandbox Code Playgroud)
并安装了您的商店应用程序(子网站为IIS中的虚拟目录,标记为应用程序)
D:\WebApps\shop
Run Code Online (Sandbox Code Playgroud)
例如,如果您致电Server.MapPath()以下请求:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
Run Code Online (Sandbox Code Playgroud)
然后:
Server.MapPath(".")1返回D:\WebApps\shop\productsServer.MapPath("..") 回报 D:\WebApps\shopServer.MapPath("~") 回报 D:\WebApps\shopServer.MapPath("/") 回报 C:\Inetpub\wwwrootServer.MapPath("/shop") 回报 D:\WebApps\shop如果Path以正斜杠(/)或反斜杠(\)开头,则MapPath()返回路径,就好像Path是一个完整的虚拟路径.
如果Path不以斜杠开头,则MapPath()返回相对于正在处理的请求的目录的路径.
注意:在C#中,@是逐字文字字符串运算符,意味着字符串应该"按原样"使用,而不是为转义序列处理.
脚注
Server.MapPath(null)并且Server.MapPath("")也会产生这种效果.dav*_*v_i 24
只是为了扩展@splattne的答案:
MapPath(string virtualPath) 调用以下内容:
public string MapPath(string virtualPath)
{
return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));
}
Run Code Online (Sandbox Code Playgroud)
MapPath(VirtualPath virtualPath)反过来调用MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping)包含以下内容:
//...
if (virtualPath == null)
{
virtualPath = VirtualPath.Create(".");
}
//...
Run Code Online (Sandbox Code Playgroud)
所以,如果你打电话MapPath(null)或MapPath(""),你有效地打电话MapPath(".")