/// <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 根路徑斜線差異。