0

I have the following function:

    public static string GetRelativePath(string fromPath, string toPath)
    {
        // we also tried the Uri solution but that does not return .. when you need to traverse
        // one up only
        // uri1 = "bla\foo"
        // uri2 = "bla\bar"
        // uri1.MakeRelaitveto(uri2) != "..\bar"
        var path = new StringBuilder(260); // MAX_PATH
        if (PathRelativePathTo(
            path,
            fromPath.Replace('/', '\\'),
            FILE_ATTRIBUTE_DIRECTORY,
            toPath.Replace('/', '\\'),
            FILE_ATTRIBUTE_DIRECTORY) == 0)
        {
            return toPath;
        }

        return path.ToString().Replace('\\', Path.DirectorySeparatorChar);
    }

    [DllImport("shlwapi.dll", SetLastError = true)]
    private static extern int PathRelativePathTo(
        StringBuilder pszPath, string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);
}

Which I call with the following testcase:

GetPathRelativeTo("C:\\somεpath", "C:\\anothεrpath").Shouldbe("..\\anothεrpath")

but instead it is returning ..\\anotherpath. Notice that the ε has been replaced by an e.

I tried using PathRelativePathToW but that works even less (other test cases fail).

Does anybody know what is going on and how I can prevent the replacement of the char?

RedX
  • 14,749
  • 1
  • 53
  • 76

1 Answers1

0

This seems to be a problem with shlwapi under the hood, not anything on the C# side.

Consider using System.Uri instead.

How do I get a relative path from one path to another in C#

j4nw
  • 2,227
  • 11
  • 26