Gar*_*hby 6 c# filesystems string-building
如果我有许多目录名称作为文字字符串或包含在变量中,那么将这些目录组合在一起以形成完整路径的最简单方法是什么?
我知道
Path.Combine但这只需要2个字符串参数,我需要一个可以采用任意数量目录参数的解决方案.
例如:
string folder1 = "foo";
string folder2 = "bar";
CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")
有任何想法吗?C#是否支持方法中的无限args?
Ore*_*ost 15
C#是否支持方法中的无限args?
是的,看看params关键字.将编写一个只调用Path.Combine适当次数的函数会很容易,就像这样(未经测试):
string CombinePaths(params string[] parts) {
string result = String.Empty;
foreach (string s in parts) {
result = Path.Combine(result, s);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
LINQ再次救援.该聚合扩展功能可以用来完成你想要的.考虑这个例子:
string[] ary = new string[] { "c:\\", "Windows", "System" };
string path = ary.Aggregate((aggregation, val) => Path.Combine(aggregation, val));
Console.WriteLine(path); //outputs c:\Windows\System
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5144 次 |
| 最近记录: |