有没有一种简单的方法可以在 C# 中组合两个相对路径?
我想在 C# 中组合两个相对路径.
I want to combine two relative paths in C#.
例如:
string path1 = "/System/Configuration/Panels/Alpha";
string path2 = "Panels/Alpha/Data";
我想回来
string result = "/System/Configuration/Panels/Alpha/Data";
我可以通过拆分第二个数组并在 for 循环中进行比较来实现这一点,但我想知道是否有类似于 Path.Combine
的东西可用,或者是否可以使用正则表达式或林克?
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?
谢谢
假设这两个字符串的格式始终与您的示例中的格式相同,这应该有效:
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"
对于 path1 = "/System/a/b/a/b"
和 path2 = "a/b/a/b/c"
结果是 "/System/a/b/a/b/a/b/c".您可以将 LastOrDefault 更改为 FirstOrDefault 以获取 "/System/a/b/a/b/c"
.
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.