Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

path2.RelativeTo(path1) doesn't work if path2 isn't inside path1 #19

Open
oxygen-dioxide opened this issue May 23, 2024 · 2 comments
Open

Comments

@oxygen-dioxide
Copy link
Contributor

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
@nemec
Copy link
Owner

nemec commented May 24, 2024

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'

@oxygen-dioxide
Copy link
Contributor Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants