Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy method to combine two relative paths in C#?

I want to combine two relative paths in C#.

For example:

string path1 = "/System/Configuration/Panels/Alpha";
string path2 = "Panels/Alpha/Data";

I want to return

string result = "/System/Configuration/Panels/Alpha/Data";

I can implement this by splitting the second array and compare it in a for loop but I was wondering if there is something similar to Path.Combine available or if this can be accomplished with regular expressions or Linq?

Thanks

like image 482
Ioannis Avatar asked Dec 04 '25 21:12

Ioannis


2 Answers

Provided that the two strings are always in the same format as in your example, this should work:

string path1 = "/System/Configuration/Panels/Alpha";
string path2 = "Panels/Alpha/Data";

var x = path1.Split('/');
var y = path2.Split('/');

string result = Enumerable.Range(0, x.Count())

                          .Where(i => x.Skip(i)
                                       .SequenceEqual(y.Take(x.Skip(i)
                                                              .Count())))

                          .Select(i => string.Join("/", x.Take(i)
                                                         .Concat(y)))

                          .LastOrDefault();

// result == "/System/Configuration/Panels/Alpha/Data"

For path1 = "/System/a/b/a/b" and path2 = "a/b/a/b/c" the result is "/System/a/b/a/b/a/b/c". You can change LastOrDefault to FirstOrDefault to get "/System/a/b/a/b/c" instead.


Note that this algorithm essentially creates all possible combinations of the two paths and isn't particularly efficient.

like image 61
dtb Avatar answered Dec 07 '25 10:12

dtb


I think this requires a-priori knowledge that certain folders are the same, something you cannot safely infer from just the path (given that it's not absolute).

You'd have to write some custom logic yourself to do the combining of these paths.

like image 29
John Weldon Avatar answered Dec 07 '25 09:12

John Weldon