I'm hoping there is a built in .NET method to do this, but I'm not finding it.
I have two paths that I know to be on the same root drive, I want to be able to get a relative path from one to the other.
string path1 = @"c:\dir1\dir2\";
string path2 = @"c:\dir1\dir3\file1.txt";
string relPath = MysteryFunctionThatShouldExist(path1, path2);
// relPath == "..\dir3\file1.txt"
Does this function exist? If not what would be the best way to implement it?
To view the full path of an individual file: Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document.
The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.
Uri
works:
Uri path1 = new Uri(@"c:\dir1\dir2\");
Uri path2 = new Uri(@"c:\dir1\dir3\file1.txt");
Uri diff = path1.MakeRelativeUri(path2);
string relPath = diff.OriginalString;
You could also import the PathRelativePathTo
function and call it.
e.g.:
using System.Runtime.InteropServices;
public static class Util
{
[DllImport( "shlwapi.dll", EntryPoint = "PathRelativePathTo" )]
protected static extern bool PathRelativePathTo( StringBuilder lpszDst,
string from, UInt32 attrFrom,
string to, UInt32 attrTo );
public static string GetRelativePath( string from, string to )
{
StringBuilder builder = new StringBuilder( 1024 );
bool result = PathRelativePathTo( builder, from, 0, to, 0 );
return builder.ToString();
}
}
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