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
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.
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.
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