常用屬性與方法對照
| 需求 | 程式碼 | 回傳範例 |
| 虛擬路徑(網站根) | Server.MapPath("~/") | D:\WebSites\MyApp\ |
| 應用程式虛擬路徑 | HttpContext.Current.Request.ApplicationPath | /MyApp |
| 應用程式物理路徑 | HttpContext.Current.Request.PhysicalApplicationPath | D:\WebSites\MyApp\ |
| 當前請求物理路徑 | HttpContext.Current.Request.PhysicalPath | D:\WebSites\MyApp\Default.aspx |
| AppDomain 基底目錄 | AppDomain.CurrentDomain.BaseDirectory | D:\WebSites\MyApp\ |
| 執行檔目錄 | Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) | D:\WebSites\MyApp\bin\ |
Global.asax 中的取用時機
void Application_Start()
{
// 此時 HttpContext.Current 為 null,需用 AppDomain 或 HostingEnvironment
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string mapPath = HostingEnvironment.MapPath("~/");
}
最佳實踐建議
- **Web 應用程式統一使用
Server.MapPath("~/...")** 或 HostingEnvironment.MapPath,可正確解析虛擬路徑且不依賴 HttpContext。
- 避免硬編碼絕對路徑,部署到不同伺服器/目錄即會失效。
- 需存取
bin 目錄下檔案時,使用 Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", "file.dll")。