在C#中,如何同时组合文件路径的两个以上部分?

Mat*_*hew 28 c# path relative-path

要组合文件路径的两个部分,您可以这样做

System.IO.Path.Combine (path1, path2);
Run Code Online (Sandbox Code Playgroud)

但是,你做不到

System.IO.Path.Combine (path1, path2, path3);
Run Code Online (Sandbox Code Playgroud)

有一个简单的方法吗?

Aar*_*ght 31

这是一个可以使用的实用方法:

public static string CombinePaths(string path1, params string[] paths)
{
    if (path1 == null)
    {
        throw new ArgumentNullException("path1");
    }
    if (paths == null)
    {
        throw new ArgumentNullException("paths");
    }
    return paths.Aggregate(path1, (acc, p) => Path.Combine(acc, p));
}
Run Code Online (Sandbox Code Playgroud)

替代代码 - 高尔夫版本(更短,但不太清晰,语义有点不同Path.Combine):

public static string CombinePaths(params string[] paths)
{
    if (paths == null)
    {
        throw new ArgumentNullException("paths");
    }
    return paths.Aggregate(Path.Combine);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这称为:

string path = CombinePaths(path1, path2, path3);
Run Code Online (Sandbox Code Playgroud)

  • 为什么额外的'path1'参数?另外,最后一行可以缩短为`return paths.Aggregate(/*path1,*/Path.Combine);` (5认同)
  • `使用System.Linq`. (2认同)
  • 啊 - "Aggregate"是`System.Linq`命名空间中的扩展方法,它位于`System.Core.dll`中. (2认同)

Jon*_*eet 24

正如其他人所说的那样,在.NET 3.5及更早版本中,没有一种方法可以做到这一点 - 你要么必须编写自己的Combine方法,要么Path.Combine多次调用.

但欢喜 - 因为在.NET 4.0中,存在这种过载:

public static string Combine(
    params string[] paths
)
Run Code Online (Sandbox Code Playgroud)

还有重载需要3或4个字符串,大概是因为它不需要为常见情况不必要地创建一个数组.

希望Mono能尽快解决这些超载问题 - 我相信它们很容易实现并且非常受欢迎.

  • 无需等待,自10/21/09开始实施:) http://anonsvn.mono-project.com/viewvc?view=revision&revision=144597 (5认同)
  • http://msdn.microsoft.com/en-us/library/dd784047(VS.90).aspx声明Path.Combine将在.Net 3.5中占用3个字符串,这显然是错误的,因为它在使用时会产生编译错误.在这种情况下,msdn库是错误的.我把它放在这里以防万一有人在得到这个编译器错误后登陆这个页面. (2认同)

Avi*_* P. 5

不简单,但很聪明:)

string str1 = "aaa", str2 = "bbb", str3 = "ccc";
string comb = new string[] { str1, str2, str3 }
    .Aggregate((x, y) => System.IO.Path.Combine(x, y));
Run Code Online (Sandbox Code Playgroud)

或者:

string CombinePaths(params string[] paths)
{
    return paths.Aggregate((x,y) => System.IO.Path.Combine(x, y));
}
Run Code Online (Sandbox Code Playgroud)

编辑Order23 的答案实际上是最新的与当前的 .NET /sf/answers/2880414071/

  • 如果您不多次这样做,这很方便。不过,您可以将其简化很多:`new [] { "aaa", "bbb", "ccc" }.Aggregate (Path.Combine);`(假设您正在使用 System.IO;`)。 (2认同)