Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a relative path from one path to another in C# [duplicate]

Tags:

c#

.net

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?

like image 959
Bert Lamb Avatar asked Nov 19 '09 21:11

Bert Lamb


People also ask

How do I find a path from one file to another?

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.

How do you convert an absolute path to a relative path?

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.


2 Answers

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;
like image 112
Marc Gravell Avatar answered Sep 23 '22 09:09

Marc Gravell


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();
  }
}
like image 29
Leviculus Avatar answered Sep 20 '22 09:09

Leviculus