20

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

Chris Gerken
  • 16,221
  • 6
  • 44
  • 59
Markus
  • 3,297
  • 4
  • 31
  • 52

1 Answers1

33

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\");
zumalifeguard
  • 8,648
  • 5
  • 43
  • 56
Sisyphe
  • 4,626
  • 1
  • 25
  • 39