Asp.net

Server.MapPath(’.’)、Server.MapPath(’~’)、Server.MapPath(@’’…

  • November 9, 2008

誰能解釋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# 中,@是逐字字面字元串運算符,表示字元串應該“按原樣”使用,而不是為轉義序列處理。

腳註

  1. Server.MapPath(null)也會Server.MapPath("")產生這種效果

引用自:https://stackoverflow.com/questions/275781