从包含文件名的路径获取不包含文件名的完整路径
System.IO.Path
中是否有任何内置内容只提供文件路径?
例如,如果我有一个字符串
@“c:\webserver\public\myCompany\configs\promo.xml”,
是否有任何BCL方法可以给我
“c:\webserver\public\myCompany\configs\”?
Is there anything built into System.IO.Path
that gives me just the filepath?
For example, if I have a string
@"c:\webserver\public\myCompany\configs\promo.xml",
is there any BCL method that will give me
"c:\webserver\public\myCompany\configs\"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Path.GetDirectoryName()
...但是您需要知道传递给它的路径确实包含文件名;它只是从路径中删除最后一位,无论是文件名还是目录名(它实际上不知道是哪一个)。您可以首先在路径上测试
File.Exists()
和/或Directory.Exists()
进行验证,看看是否需要调用Path.GetDirectoryName
Path.GetDirectoryName()
... but you need to know that the path you are passing to it does contain a file name; it simply removes the final bit from the path, whether it is a file name or directory name (it actually has no idea which).You could validate first by testing
File.Exists()
and/orDirectory.Exists()
on your path first to see if you need to callPath.GetDirectoryName
Path.GetDirectoryName()
返回目录名称,因此对于您想要的内容(带有尾随反向斜线字符),您可以调用Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar
。Path.GetDirectoryName()
returns the directory name, so for what you want (with the trailing reverse solidus character) you could callPath.GetDirectoryName(filePath) + Path.DirectorySeparatorChar
.使用
GetParent()
如图所示,效果很好。 根据需要添加错误检查。Use
GetParent()
as shown, works nicely. Add error checking as you need.我用过这个并且效果很好:
I used this and it works well:
文件或目录可能并不总是位于磁盘上。比 File.Exists() 和/或 Directory.Exists() 条件更好,我们可以使用:
A file or directory may not always be on disk. better than File.Exists() and/or Directory.Exists() conditions, we can use: