9

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.

Anton Krouglov
  • 3,077
  • 2
  • 29
  • 50
  • Try import the `System.Runtime.Extensions.dll` from dotnetcore. If you have problems with classes with the same name, because .net framework already have a `System.IO` namespace, check [this answer](https://stackoverflow.com/a/3672987/5762332) – Magnetron Jul 04 '18 at 18:41
  • 1
    @Magnetron How do I _import the System.Runtime.Extensions.dll from dotnetcore_? – Anton Krouglov Jul 04 '18 at 20:15
  • Yeah, it was just a thought because that's the assembly the article says it belongs to. I tried here but I couldn't do it. The nuget version gave me no classes, so I built a dotnet core app to pick the assembly, it gave me some classes but didn't gave me the Path class. – Magnetron Jul 05 '18 at 00:05

1 Answers1

10

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;
}
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77