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?
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
}
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