pathlib
pathlib copied to clipboard
`path2.RelativeTo(path1)` doesn't work if `path2` isn't inside `path1`
In System.IO, Path.GetRelativePath(pathstr1, pathstr2) doesn't require that pathstr2 is inside pathstr1
using System.IO;
string pathstr1 = "E:/a";
string pathstr2 = "E:/a/b";
Console.WriteLine(Path.GetRelativePath(pathstr1, pathstr2)); // "b"
Console.WriteLine(Path.GetRelativePath(pathstr1, pathstr1)); // "."
Console.WriteLine(Path.GetRelativePath(pathstr2, pathstr1)); // ".."
However, In PathLib, running path2.RelativeTo(path1) when path2 isn't inside path1 will throw an error:
using PathLib;
IPath path1 = Paths.Create("E:/a");
IPath path2 = Paths.Create("E:/a/b");
Console.WriteLine(path2.RelativeTo(path1)); // "b"
Console.WriteLine(path1.RelativeTo(path1)); // error
Console.WriteLine(path1.RelativeTo(path2)); // error
You're right, it does behave differently. I based the behavior off of Python's pathlib library which does throw an error, so I guess that's where the difference comes from.
>>> import pathlib
>>> p1 = pathlib.PurePath('E:/a')
>>> p2 = pathlib.PurePath('E:/a/b')
>>> p1.relative_to(p2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/pathlib.py", line 682, in relative_to
raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
ValueError: 'E:/a' is not in the subpath of 'E:/a/b'
However, there is still a difference. In python's pathlib, relative_to works on two paths that are the same and returns ..
>>> import pathlib
>>> p1=pathlib.PurePath('E:/a')
>>> p1.relative_to(p1)
PureWindowsPath('.')
In C#'s PathLib, this will throw an error