System.IO.Abstractions icon indicating copy to clipboard operation
System.IO.Abstractions copied to clipboard

Path.GetRelativePath returns inconsistent results

Open antonyoni opened this issue 4 years ago • 3 comments

Describe the bug

On windows, when using MockFileSystem().Path.GetRelativePath and the relativeTo path does not have a drive specified, the result is inconsistent depending on what drive you run the code on.

To Reproduce

var fs = new MockFileSystem();
fs.AddDirectory("/dir/subdir");
foreach (var d in fs.Directory.GetDirectories("/dir")) {
    Console.WriteLine(d);
    var relPath = fs.Path.GetRelativePath("/dir", d);
    Console.WriteLine(relPath);
}

If I run this from the c drive (c:\temp\io-test), the output is:

C:\dir\subdir
subdir

But running it from the d drive, results in:

C:\dir\subdir
C:\dir\subdir

Expected behavior

subdir on both c and d drives.

Additional context

PathWrapper.GetRelativePath calls to the System.IO.Path.GetRelativePath which in turn calls to System.IO.Path.GetFullPath (https://github.com/dotnet/runtime/blob/01b7e73cd378145264a7cb7a09365b41ed42b240/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs#L882) which returns D:\dir for /dir.

We use paths without drive letters to make the tests compatible with both linux and windows. Guess the fix would be to implement GetRelativePath in PathWrapper, or to make MockFileSystem use the same root drive as System.IO?

antonyoni avatar May 13 '21 15:05 antonyoni

@antonyoni Thanks for reporting this issue! How does your snippet behave when using FileSystem instead of MockFileSystem?

fgreinacher avatar May 15 '21 20:05 fgreinacher

Running from both drives, same output:

/dir\subdir
subdir

But it's checking for dir on the same drive as the working directory. Removing, C:\dir when running from the C drive results in:

Unhandled exception. System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\dir'.

antonyoni avatar May 18 '21 20:05 antonyoni

Thanks for providing additional information! MockFileSystem should generally behave as close to FileSystem as possible, so that should be the goal for the fix.

Marking it as ready, but I probably won't find the time for investigating deeper in the next weeks, so a PR would be super welcome 😀

fgreinacher avatar May 24 '21 16:05 fgreinacher