Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute to Relative path [duplicate]

Tags:

c#

path

I'm getting a file from an OpenFileDialog which returns a string with the absolute path to the selected file. Now I want that path as a relative path to a given path (in this case the path to my application).

So let's say I get a path to the file: c:\myDock\programming\myProject\Properties\AssemblyInfo.cs

and my application is located in

c:\myDock\programming\otherProject\bin\Debug\program.exe

then I want the result:

..\..\..\myProject\Properties\AssemblyInfo.cs

like image 671
Markus Avatar asked Nov 07 '12 09:11

Markus


1 Answers

The Uri class has a MakeRelativeUri method that can help.

public static string MakeRelative(string filePath, string referencePath)
{
    var fileUri = new Uri(filePath);
    var referenceUri = new Uri(referencePath);
    return Uri.UnescapeDataString(referenceUri.MakeRelativeUri(fileUri).ToString()).Replace('/', Path.DirectorySeparatorChar);
}

var result = MakeRelative(@"C:\dirName\dirName2\file.txt", @"C:\dirName\");
like image 59
Sisyphe Avatar answered Oct 13 '22 00:10

Sisyphe