string path = System.IO.Path.GetDirectoryName(Page.Request.PhysicalPath);
// 結果範例:D:\WebSites\MyProject\SubFolder
string path = HttpContext.Current.Request.MapPath("~/");
// 結果:網站實體根目錄,如 D:\WebSites\MyProject\
優點:可在非 Page 類別(如 HttpModule、Service、Class Library)中使用,路徑基準明確。
string path = Page.Server.MapPath("~/");
// 結果同方法二,但需在 Page/Control 內容中呼叫。
| 方法 | 適用範圍 | 回傳範例 | 備註 |
|---|---|---|---|
| Path.GetDirectoryName(Request.PhysicalPath) | .aspx/.ascx 程式碼後置 | 目前檔案所在目錄 | 若在 Master Page 中會取得 Master 所在目錄 |
| HttpContext.Current.Request.MapPath("~") | 任何有 HttpContext 的地方 | 網站根目錄 | 最通用、推薦 |
| Server.MapPath("~") | Page/UserControl 內 | 網站根目錄 | 內部呼叫 HttpContext.Current.Request.MapPath |
MapPath("~/Uploads/")MapPath("~/App_Data/config.xml")若遇到「找不到類型」錯誤,請確認專案已參考 System.Web.dll。