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,053
  • 6
  • 43
  • 58
Markus
  • 3,197
  • 4
  • 30
  • 49

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,245
  • 5
  • 39
  • 52
Sisyphe
  • 4,588
  • 1
  • 23
  • 39