c#写一个函数算出两个文件的相对路径

如$a=‘/a/b/c/d/e.php’;

$b='/a/b/12/34/c.php';

计算出$b相对于$a的相对路径应该是../../c/d

个人答案如下:

首先我感觉b相对于a的路径应该是../../12/34才对,a相对于b才是../../c/d

函数如下,求path1相对于path2的相对路径

public static string getPath2(string path1, string path2)
        {
            string result = "";
            string tempstr = "";
            string[] arr1 = path1.Split('/');
            string[] arr2 = path2.Split('/');
            int parentNum = 0;
            if (arr2.Length > arr1.Length)
            {
                parentNum= arr2.Length - arr1.Length;
            }
            
            for (int i = 0; i < arr1.Length - 1; i++)
            {
                if (i < arr2.Length && arr1[i] == arr2[i])
                {
                    continue;
                }
                else
                {
                    result += result == "" ? arr1[i] : "/" + arr1[i];
                    parentNum++;
                }
            }
            if (parentNum > 0)
            {
                for (int i = 0; i < parentNum; i++)
                {
                    tempstr += tempstr == "" ? ".." : "/..";
                }
                result = tempstr + (result == "" ? "" : "/" + result);
            }
            return result;
        }

测试结果:

public static void Main()
{
   Console.WriteLine(getPath2("/a/c/a.txt","/a/b/c/d/b.txt"));
   Console.WriteLine(getPath2("/a/b/c/d/e/f/a.txt", "/a/b/c/d/b.txt"));
   Console.WriteLine(getPath2("/a/b/12/34/a.txt", "/a/b/c/d/b.txt"));
   Console.ReadKey();
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章