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)
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能尽快解决这些超载问题 - 我相信它们很容易实现并且非常受欢迎.
不简单,但很聪明:)
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/
| 归档时间: |
|
| 查看次数: |
12266 次 |
| 最近记录: |