Server.MapPath(string path)作用是返回與Web服務器上的指定虛擬路徑相對應的物理文件路徑。其參數path為Web 服務器的虛擬路徑,返回結果是與path相對應的物理文件路徑。但有時參數並非為虛擬路徑,而是用戶自定義的文件名。
Server.MapPath()的全名是System.Web.HttpContext.Current.Server.MapPath()。有時在程序調試時會提示“當前上下文中不存在名稱“Server””錯誤,從而不支持函數Server.MapPath()的使用。盡管引用了命名空間“using System.Web;”也是無濟於事,此時就需要使用其全名,或者是當前使用Server.MapPath()函數的類繼承自System.Web.UI.Page。
Server.MapPath("") :返回當前頁面所在的物理文件路徑
Server.MapPath("/") :返回應用程序根目錄所在的物理文件路徑
Server.MapPath("./") :返回當前頁面所在的物理文件路徑
Server.MapPath("../"):返回當前頁面所在的上一級的物理文件路徑
Server.MapPath("~/"):返回應用程序的虛擬目錄(路徑)
Server.MapPath("~"):返回應用程序的虛擬目錄(路徑)
說明:對於Server.MapPath()具體返回什么內容,在不同的環境下得到的結果也許並不相同。
用法:
1.Server.MapPath("/") 應用程序根目錄所在的位置 如 C:\Inetpub\wwwroot\
2.Server.MapPath("./") 表示所在頁面的當前目錄 ( 注:等價於Server.MapPath("") 返回 Server.MapPath("")所在頁面的物理文件路徑)
3.Server.MapPath("../")表示上一級目錄
4.Server.MapPath("~/")表示當前應用級程序的目錄
如果是根目錄,就是根目錄;
如果是虛擬目錄,就是虛擬目錄所在的位置 如:C:\Inetpub\wwwroot\Example\
注:等效於Server.MapPath("~")。
當前的網站目錄為E:\wwwroot
應用程序虛擬目錄為E:\wwwroot\company
瀏覽的頁面路徑為E:\wwwroot\company\news\show.asp
在show.asp頁面中使用
Server.MapPath("./") 返回路徑為:E:\wwwroot\company\news
Server.MapPath("/") 返回路徑為:E:\wwwroot
Server.MapPath("../") 返回路徑為:E:\wwwroot\company
Server.MapPath("~/") 返回路徑為:E:\wwwroot\company
server.MapPath(request.ServerVariables("Path_Info"))
Request.ServerVariables("Path_Translated")
上面兩種方式返回路徑為 D:\wwwroot\company\news\show.asp