首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

Global.asax 中取得應用程式物理路徑、虛擬路徑與絕對路徑的方法總覽

     編輯:ASP.NET 基礎

常用屬性與方法對照

需求程式碼回傳範例
虛擬路徑(網站根)Server.MapPath("~/")D:\WebSites\MyApp\
應用程式虛擬路徑HttpContext.Current.Request.ApplicationPath/MyApp
應用程式物理路徑HttpContext.Current.Request.PhysicalApplicationPathD:\WebSites\MyApp\
當前請求物理路徑HttpContext.Current.Request.PhysicalPathD:\WebSites\MyApp\Default.aspx
AppDomain 基底目錄AppDomain.CurrentDomain.BaseDirectoryD:\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")。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved