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

ASP.NET 將 Web 站點下的絕對路徑轉換為虛擬路徑

     編輯:關於ASP.NET

兩個實用轉換方法

方法一:相對於指定頁面的虛擬路徑

/// <summary>
/// 將 Web 站點下的絕對路徑轉換為相對於指定頁面的虛擬路徑
/// </summary>
/// <param name="page">當前頁面指標,通常為 this</param>
/// <param name="specifiedPath">絕對路徑</param>
/// <returns>虛擬路徑,如 ../../xxx</returns>
public static string ConvertSpecifiedPathToRelativePathForPage(Page page, string specifiedPath)
{
    string virtualPath = page.Request.ApplicationPath;          // 根虛擬路徑
    string pathRooted = HostingEnvironment.MapPath(virtualPath); // 根絕對路徑
    string pageVirtualPath = page.Request.Path;                 // 頁面虛擬路徑

    if (!Path.IsPathRooted(specifiedPath) || specifiedPath.IndexOf(pathRooted) == -1)
        throw new Exception(string.Format("\"{0}\"是虛擬路徑而非絕對路徑!", specifiedPath));

    // 處理根路徑結尾斜線差異(VS 開發伺服器 vs IIS)
    if (pathRooted.Substring(pathRooted.Length - 1, 1) == "\\")
        specifiedPath = specifiedPath.Replace(pathRooted, "/");
    else
        specifiedPath = specifiedPath.Replace(pathRooted, "");

    string relativePath = specifiedPath.Replace("\\", "/");
    string[] pageNodes = pageVirtualPath.Split('/');
    int pageNodesCount = pageNodes.Length - 2; // 減去頁面名與前導空字串

    for (int i = 0; i < pageNodesCount; i++)
        relativePath = "/.." + relativePath;

    if (pageNodesCount > 0)
        relativePath = relativePath.Substring(1); // 移除最前面的 "/"

    return relativePath;
}

核心邏輯:取得應用程式根絕對路徑、頁面虛擬路徑層級,計算相對層數(../),組合成相對虛擬路徑。兼容 VS 內建伺服器與 IIS 根路徑斜線差異。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved