Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Path.GetRelativePath (.NET Core2) in WinForms proj targeting 4.7.1?

Tags:

c#

.net

.net-core

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.

like image 224
Anton Krouglov Avatar asked Jul 04 '18 18:07

Anton Krouglov


People also ask

How do I find the relative path of a directory?

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.


1 Answers

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;
}
like image 156
Cee McSharpface Avatar answered Oct 02 '22 10:10

Cee McSharpface