Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove part of a path from another path?

Tags:

c#

I have two file paths like this:

var path1 = "c:\dir\anotherdir";
var path2 = "c:\dir\anotherdir\yetanotherdir\dirception\file.zip";
var result = path2 - path1; //Wanted result: yetanotherdir\dirception\file.zip

What I need to do, is to take the path1 and "remove" it from the path2.

Now the easiest solution would be to simply use substr, or something, and simply cut out the path1 from the path2 in a "text" way. But I would rather used some actual inbuilt functions in c#, intended for working with paths, to handle this.

I tried this:

var result = (new Uri(path1)).MakeRelativeUri(path2);

Expected result: yetanotherdir\dirception\file.zip

Actual result: anotherdir\yetanotherdir\dirception\file.zip

What is the best way to achieve my goal then?

like image 648
Userman Avatar asked Sep 16 '25 08:09

Userman


1 Answers

Path.GetFullPath, String.StartsWith and String.Substring should be reliable enough:

string path1 = @"c:\dir\anotherdir";
string path2 = @"c:\dir\anotherdir\yetanotherdir\dirception\file.zip";
string fullPath1 = Path.GetFullPath(path1);
string fullPath2 = Path.GetFullPath(path2);
if (fullPath2.StartsWith(fullPath1, StringComparison.CurrentCultureIgnoreCase))
{
    string result = fullPath2.Substring(fullPath1.Length).TrimStart(Path.DirectorySeparatorChar);
    // yetanotherdir\dirception\file.zip
}
like image 66
Tim Schmelter Avatar answered Sep 17 '25 23:09

Tim Schmelter