SoFunction
Updated on 2025-03-07

C# Example code of the relative directory algorithm for calculating two files


public string GetRelativePath(string path1, string path2)
{
            string[] path1Array = ('/');
            string[] path2Array = ('/');
            //
            int s = >= ? : ;
//The shared directory index at the lowest level of the two directories
            int closestRootIndex = -1;
            for (int i = 0; i < s; i++)
            {
                if (path1Array[i] == path2Array[i])
                {
                    closestRootIndex = i;
                }
                else
                {
                    break;
                }
            }
// Calculate from path1 ‘../’ part
            string path1Depth = "";
            for (int i = 0; i < ; i++)
            {
                if (i > closestRootIndex + 1)
                {
                    path1Depth += "../";
                }
            }
// Calculate from path2 the directory after ‘../’
            string path2Depth = "";
            for (int i = closestRootIndex + 1; i < ; i++)
            {
                path2Depth += "/" + path2Array[i];
            }
            path2Depth = (1);

            return path1Depth + path2Depth;
}