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
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\");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With