Userman
Userman

Reputation: 43

How to remove part of a path from another path?

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?

Upvotes: 4

Views: 6765

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460098

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
}

Upvotes: 6

PaddyD
PaddyD

Reputation: 1157

If you add an extra path separator char on the end of path1 so it becomes:

var path1 = "c:\dir\anotherdir\";

Then the following should work:

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

Upvotes: 1

Noctis
Noctis

Reputation: 11763

var path1 = @"c:\dir\anotherdir";
var path2 = @"c:\dir\anotherdir\yetanotherdir\dirception\file.zip";
var path3 = path2.Replace(path1,""); // Will hold : \yetanotherdir\dirception\file.zip

You can remove the first \ if you want. But out of curiosity, why wouldn't you want the prefix of the path?

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

You can just replace it out

var result = path2.Replace(path1+"/","");

Upvotes: 1

Related Questions