C#相对地址转绝对路径

csharp

浏览数:298

2019-1-7

AD:资源代下载服务


ToAbsolutePath

// var absolutePath = "/aa/bb/cc/dd.js";
// var relativePath = "../../cc.css";
// relativePath=ToAbsolutePath(relativePath, absolutePath)
// relativePath="/aa/cc.css";

/// <summary>
/// 将相对地址转换成绝对地址
/// </summary>
/// <param name="source">需要转换的相对地址</param>
/// <param name="absolutePath">绝对地址</param>
/// <returns></returns>
public static string ToAbsolutePath(this string source, string absolutePath)
{
    //是否包含文件名,比如/aa/bb/cc/dd.js,
    if (System.IO.Path.HasExtension(absolutePath))
    {
        //去掉文件名获取路径
        var fileName = System.IO.Path.GetFileName(absolutePath);
        if (fileName != null) absolutePath = absolutePath.Replace(fileName, "");
    }    //去掉开头“./”
    var elativePath = source.StartsWith("./") ? source.Substring(2): source;

    //组合路径
    //如果是“/”结尾,则直接组合 "/aa/bb/cc/", "../../cc.css" => "/aa/bb/cc/../../cc.css"
    //如果不是,则连接处转成 "/aa/bb/cc", "../../cc.css" => "/aa/bb/cc\\../../cc.css"
    var aPath = System.IO.Path.Combine(absolutePath, elativePath.TrimStart('.').TrimStart('/'));

    //处理包含“..”的路径
    while (aPath.Contains(".."))
    {
        //将“..”连同前一个路径去掉 "/aa/bb/cc/../../cc.css" => "/aa/bb/../cc.css"
        aPath = System.Text.RegularExpressions.Regex.Replace(aPath, @"((/|\\)\w+(/|\\)\.\.(/|\\))", "/");
    }

    // aPath = "/aa/cc.css"
    return aPath;
}