Ioannis
Ioannis

Reputation: 3045

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

Upvotes: 3

Views: 890

Answers (4)

Steve Dennis
Steve Dennis

Reputation: 1373

Path.GetFullPath(Path.Combine(path1, path2))

GetFullPath will merge and simplify the resulting path.

EDIT: Never mind, that only works for absolute paths...

Upvotes: 0

dtb
dtb

Reputation: 217341

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.

Upvotes: 5

pblasucci
pblasucci

Reputation: 1778

Try this...

var p1 = path1.Split('/');
var p2 = path2.Split('/');

result = p1.Union(p1);

It uses System.Linq, and can easily be packaged into an extension method.

Of course, it assumes something about the values of path1 and path2.

Upvotes: 0

John Weldon
John Weldon

Reputation: 40789

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.

Upvotes: 4

Related Questions