Get Relative Path

3. April 2008 04:24 by Mrojas in General  //  Tags: , , ,   //   Comments (0)

I had the requirement of creating a MSBuild custom task that opens a .csproj
adds a reference to another project.

The problem I faced is that references in VisualStudio are generated as relative paths,
so I needed something to help me generate relative paths.

After some Googleing I finally found this code. It was in a long forum discussion
and was posted by a guy named something like Marcin Grzabski. And here it is for posterity.

        private static string EvaluateRelativePath(string mainDirPath, string absoluteFilePath)
        {
            string[]
            firstPathParts = 
             mainDirPath.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar);
            string[]
            secondPathParts = 
             absoluteFilePath.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar);
 
            int sameCounter = 0;
            for (int i = 0; i < Math.Min(firstPathParts.Length,secondPathParts.Length); i++)
            {
                if (
                !firstPathParts[i].ToLower().Equals(secondPathParts[i].ToLower()))
                {
                    break;
                }
                sameCounter++;
            }
 
            if (sameCounter == 0)
            {
                return absoluteFilePath;
            }
 
            string newPath = String.Empty;
            for (int i = sameCounter; i < firstPathParts.Length; i++)
            {
                if (i > sameCounter)
                {
                    newPath += Path.DirectorySeparatorChar;
                }
                newPath += "..";
            }
            if (newPath.Length == 0)
            {
                newPath = ".";
            }
            for (int i = sameCounter; i < secondPathParts.Length; i++)
            {
                newPath += Path.DirectorySeparatorChar;
                newPath += secondPathParts[i];
            }
            return newPath;
        }

And to use is just do somelines like:

 

            String test = EvaluateRelativePath(@"E:\Source_Code\Code\ProjectsGroup1\Project1", @"E:\Source_Code\Code\ProjecstGroup2\Project2");
 
//This will genearate something like ..\..\ProjectGroup2\Project2