This seems to be a pretty simple question, yet googling yield nothing useful.
I have VS2017 WinForms C# project targeting .NET Framework 4.7.1.
I would like to make use of Path.GetRelativePath from .NET Core 2.X.
Is it achievable (nuget package or something)?
PS. For those who are lazy to port .NET Core code themselves here is my adapted version of it.
Windows Interop Answer. There is a Windows API called PathRelativePathToA that can be used to find a relative path. Please note that the file or directory paths that you pass to the function must exist for it to work.
A workaround: If for some reason, the Core library cannot be referenced or called at runtime, you can implement the function yourself, it is quite simple:
public string GetRelativePath(string relativeTo, string path)
{
var uri = new Uri(relativeTo);
var rel = Uri.UnescapeDataString(uri.MakeRelativeUri(new Uri(path)).ToString()).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
if (rel.Contains(Path.DirectorySeparatorChar.ToString()) == false)
{
rel = $".{ Path.DirectorySeparatorChar }{ rel }";
}
return rel;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With