1

I have an absolute folder path and files path like following:

C:\BaseDir - base folder

C:\BaseDir\sub\123.txt - path to file that is located in base folder (but maybe also with some subfolders)

Another example of file path: C:\BaseDir\file.docx or C:\BaseDir\sub\sub1\file.exe

I need to convert pathes to files from absolute to relative based on the base folder. Results should look like following: sub\123.txt ; file.docx ; sub\sub1\file.exe

Please note, that I don't want BaseDir in path. Solution should also work with network folders(\\Server1\BaseDir\file.docx or \\172.31.1.60\BaseDir\sub\123.txt).

Are there any built in classes that do this?

steavy
  • 1,483
  • 6
  • 19
  • 42

3 Answers3

2

Credits goes do this post: Absolute to Relative path

public static string AbsoluteToRelativePath(string pathToFile, string referencePath)
{
    var fileUri = new Uri(pathToFile);
    var referenceUri = new Uri(referencePath);
    return referenceUri.MakeRelativeUri(fileUri).ToString();
}

Now you can use this like

var result = AbsoluteToRelativePath(@"C:\dir\path\to\file.txt", @"C:\dir\");
  • It does not work! E.g.: filepath="c:\a\b.txt", the basepath="c:\x", then I expect the result: "..\a\b.txt". But it has different result. *EDIT:* sorry, it works, but basepath must end with "\", so "c:\x\" – Zoli Mar 10 '22 at 08:18
0

You could use the MakeRelativeUri method:

var basePath = @"C:\BaseDir\";
var path = @"C:\BaseDir\sub\file.docx";
var result = new Uri(basePath).MakeRelativeUri(new Uri(path));
Console.WriteLine(Uri.UnescapeDataString(result.ToString()));
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

There is another option when using .NET Core 2 or newer:

var basePath = @"C:\BaseDir\";
var path = @"C:\BaseDir\sub\file.docx";
var relative = Path.GetRelativePath(basePath, path);

The difference (might an advantage) to Uri is, that the path gets not escaped. When using Uri, spaces gets replaced by %20 etc.

SommerEngineering
  • 1,412
  • 1
  • 20
  • 26