IIS7.5部署站點後獲取檔案物理路徑及web虛擬路徑、以及獲取通過Request.Uri獲取部署地址資訊
阿新 • • 發佈:2019-01-07
1、在部署到IIS後,我們儲存檔案需要獲取實際實體地址及web虛擬地址,可以通過以下方式獲取:
通過Hosting.HostingEnviroment獲取實體地址和虛擬地址
var appPhysicalPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;//web程式部署實體地址,例如:D:\TFS\Energe var appVirtualPath = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;//web程式虛擬根目錄,例如:/GGFW var localPath = appPhysicalPath + path;//伺服器檔案儲存路徑,path是相對路徑 PathToList = appVirtualPath.TrimEnd('/') + path;//web虛擬路徑,path是相對路徑
2、asp.net通過uri直接獲取部署地址,利用GetLeftPart 方法獲取。
GetLeftPart 方法返回一個包含 URI 字串中最左邊部分的字串,它以 part 指定的部分結束。
在下面的情況下,GetLeftPart 包括分隔符:
下面的示例演示一個 URI 以及使用 Scheme、Authority、Path 或 Query 呼叫 GetLeftPart 的結果。
利用該方法獲取地址程式碼如下:
public static string GetRootURI() { string AppPath = ""; HttpContext HttpCurrent = HttpContext.Current; HttpRequest Req; if (HttpCurrent != null) { Req = HttpCurrent.Request; string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority); if (Req.ApplicationPath == null || Req.ApplicationPath == "/") //直接安裝在 Web 站點 AppPath = UrlAuthority; else //安裝在虛擬子目錄下 AppPath = UrlAuthority + Req.ApplicationPath; } return AppPath; }