steavy
steavy

Reputation: 1576

To relative path from base absolute

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?

Upvotes: 2

Views: 1430

Answers (3)

SommerEngineering
SommerEngineering

Reputation: 1700

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.

Upvotes: 1

Sebastian Richter
Sebastian Richter

Reputation: 485

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\");

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039418

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()));

Upvotes: -1

Related Questions