在 C# 中,如何一次组合文件路径的两个以上部分?
要组合文件路径的两部分,您可以执行此操作
System.IO.Path.Combine (path1, path2);
但是,您不能执行
System.IO.Path.Combine (path1, path2, path3);
此操作是否有一种简单的方法可以执行此操作?
To combine two parts of a file path, you can do
System.IO.Path.Combine (path1, path2);
However, you can't do
System.IO.Path.Combine (path1, path2, path3);
Is there a simple way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是您可以使用的实用方法:
备用代码高尔夫版本(更短,但不太清楚,语义与
Path.Combine
有点不同):然后您可以将其称为:
Here's a utility method you can use:
Alternate code-golf version (shorter, but not quite as clear, semantics are a bit different from
Path.Combine
):Then you can call this as:
正如其他人所说,在 .NET 3.5 及更早版本中,还没有一种方法可以巧妙地做到这一点 - 您要么必须编写自己的
Combine
方法,要么调用Path.Combine多次。
但庆幸的是,在 .NET 4.0 中,存在此重载< /a>:
还有需要 3 或 4 个字符串的重载,大概这样就不需要在常见情况下创建不必要的数组。
希望 Mono 能够尽快移植这些重载 - 我相信它们会很容易实现并且非常受欢迎。
As others have said, in .NET 3.5 and earlier versions there hasn't been a way to do this neatly - you either have to write your own
Combine
method or callPath.Combine
multiple times.But rejoice - for in .NET 4.0, there is this overload:
There are also overloads taking 3 or 4 strings, presumably so that it doesn't need to create an array unnecessarily for common cases.
Hopefully Mono will port those overloads soon - I'm sure they'd be easy to implement and much appreciated.
不简单,但是很聪明:)
或者:
编辑 Order23 的答案实际上是最新的.NET https: //stackoverflow.com/a/41148772/235648
Not simple, but clever :)
Or:
EDIT Order23's answer is actually up to date with current .NET https://stackoverflow.com/a/41148772/235648
不可以 - 您必须多次调用
Path.Combine()
。不过,您可以编写一个帮助器方法来为您完成此操作:
Nope - you have to call
Path.Combine()
several times.You could write a helper method that does it for you, though:
使用 .NET 4 中引入的方法重载
Path.Combine(string [])
With the method overload introduced in .NET 4
Path.Combine(string [])