国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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

2019-11-18 17:14:21
字體:
來源:轉載
供稿:網友

很經常使用到的一個功能,但在在網上卻一直沒有找到相關的解決方法,今天借著項目應用到的機會寫了兩個將絕對路徑轉換為虛擬路徑封裝好的方法
將Web站點下的絕對路徑轉換為相對于指定頁面的虛擬路徑
/**//// <summary>
/// 將Web站點下的絕對路徑轉換為相對于指定頁面的虛擬路徑
/// </summary>
/// <param name="page">當前頁面指針,一般為this</param>
/// <param name="specifiedPath">絕對路徑</param>
/// <returns>虛擬路徑, 型如: ../../</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));
    }

    // 轉換成相對路徑
    //(測試發現,pathRooted 在 VS2005 自帶的服務器跟在IIS下根目錄或者虛擬目錄運行似乎不一樣,
    // 有此地方后面會加"/", 有些則不會, 為保險起見判斷一下)
    if (pathRooted.Substring(pathRooted.Length - 1, 1) == "http://")
    {
        specifiedPath = specifiedPath.Replace(pathRooted, "/");
    }
    else
    {
        specifiedPath = specifiedPath.Replace(pathRooted, "");
    }

    string relativePath = specifiedPath.Replace("http://", "/");

    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, relativePath.Length - 1);
    }

    return relativePath;
}

第二個方法顯然是從第一個方法中的前部分抽取出來的,所以懶得去添加相關注釋 :P
將Web站點下的絕對路徑轉換為虛擬路徑
/**//// <summary>
/// 將Web站點下的絕對路徑轉換為虛擬路徑
/// 注:非Web站點下的則不轉換
/// </summary>
/// <param name="page">當前頁面指針,一般為this</param>
/// <param name="specifiedPath">絕對路徑</param>
/// <returns>虛擬路徑, 型如: ~/</returns>
public static string ConvertSpecifiedPathToRelativePath(Page page, string specifiedPath)
{
    string virtualPath = page.Request.ApplicationPath;

    string pathRooted = HostingEnvironment.MapPath(virtualPath);

    if (!Path.IsPathRooted(specifiedPath) || specifiedPath.IndexOf(pathRooted) == -1)
    {
        return specifiedPath;
    }

    if (pathRooted.Substring(pathRooted.Length - 1, 1) == "http://")
    {
        specifiedPath = specifiedPath.Replace(pathRooted, "~/");
    }
    else
    {
        specifiedPath = specifiedPath.Replace(pathRooted, "~");
    }

    string relativePath = specifiedPath.Replace("http://", "/");
    return relativePath;
}

將虛擬路徑轉絕對路就沒什么好說的了, HttPRequest.MapPath 方法專門干這事


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新乐市| 浦县| 柞水县| 黄平县| 镇宁| 报价| 凤凰县| 涞源县| 田东县| 静海县| 白山市| 洪江市| 阳城县| 长海县| 云霄县| 南安市| 屏南县| 肇东市| 肥东县| 秦皇岛市| 泊头市| 永昌县| 临清市| 丰台区| 永吉县| 隆回县| 福州市| 江津市| 日喀则市| 鸡东县| 苏尼特右旗| 朝阳市| 鄂伦春自治旗| 钟祥市| 襄樊市| 吉安市| 盖州市| 丰原市| 临武县| 横山县| 六安市|