C calculates the instance code of the two files' relative directory algorithm

  • 2020-05-17 06:17:59
  • OfStack

Building advocate big newbie 1, write technical blog for the first time, if there is a concept error or code is not standard place, also ask you to criticize and correct. Without further ado:

A while ago, I developed a user control, which called a lot of css, js and other resource files, and the directory where the page of the reference control is located is different. The problem arises: if the directory is different, the path to the css reference and js resource files in the control will change accordingly. Now that you know the path of two files relative to the root of your site, how do you calculate the relative path? Look at the code:


public string GetRelativePath(string path1, string path2)
{
            string[] path1Array = path1.Split('/');
            string[] path2Array = path2.Split('/');
            //
            int s = path1Array.Length >= path2Array.Length ? path2Array.Length : path1Array.Length;
            // Common directory index at the bottom level of both directories 
            int closestRootIndex = -1;
            for (int i = 0; i < s; i++)
            {
                if (path1Array[i] == path2Array[i])
                {
                    closestRootIndex = i;
                }
                else
                {
                    break;
                }
            }
            // by path1 To calculate   ' ../' Part of the 
            string path1Depth = "";
            for (int i = 0; i < path1Array.Length; i++)
            {
                if (i > closestRootIndex + 1)
                {
                    path1Depth += "../";
                }
            }
            // by path2 To calculate   ' ../' Back catalogue 
            string path2Depth = "";
            for (int i = closestRootIndex + 1; i < path2Array.Length; i++)
            {
                path2Depth += "/" + path2Array[i];
            }
            path2Depth = path2Depth.Substring(1);
            return path1Depth + path2Depth;
}

In my algorithm, step 1 calculates the lowest parent directory of the two directories, and step 2 calculates the number of times directory 1 needs to return to the higher directory (.. Step 3: find the relative path from the lowest parent directory to directory 2. Step 4: add the results of step 2 and step 3: that's the answer.

Calling part:


string path1 = "/Manage/Permissions/RoleManage.aspx";
string path2 = "/Manage/plugin/jquery-easyui/jquery.easyui.min.js";
string result = GetRelativePath(path1, path2);

Get results:.. / plugin/jquery - easyui/jquery easyui. min. js


Related articles: