Directory.GetFiles:如何让只有文件名,而不是完整的路径? [英] Directory.GetFiles: how to get only filename, not full path?

查看:1433
本文介绍了Directory.GetFiles:如何让只有文件名,而不是完整的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
如何使用C#得到一个目录下的文件名只?

使用C#,我希望得到一个文件夹中的文件列表结果
我的目标: [FILE1.TXT, FILE2.TXT]

Using C#, I want to get the list of files in a folder.
My goal: ["file1.txt", "file2.txt"]

所以我写了这一点:

string[] files = Directory.GetFiles(dir);



不幸的是,我得到这样的输出: [C:\\ dir\\file1.txt,C:\\dir\\file2.txt]

我可以剥离不必要的C:\dir\?部分之后,但有一个更好的解决方案。

I could strip the unwanted "C:\dir\" part afterward, but is there a more elegant solution?

推荐答案

您可以使用 System.IO.Path.GetFileName 来做到这一点。

You can use System.IO.Path.GetFileName to do this.

例如,

string[] files = Directory.GetFiles(dir);
foreach(string file in files)
    Console.WriteLine(Path.GetFileName(file));



虽然你可以使用的FileInfo ,它是比你已经在使用(只是检索文件路径)的做法更重量级的。所以我建议你还是坚持使用的GetFiles 除非你需要在的FileInfo 类的附加功能。

While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles unless you need the additional functionality of the FileInfo class.

这篇关于Directory.GetFiles:如何让只有文件名,而不是完整的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆