C# Directory.GetFiles:如何只获取文件名,而不是完整路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12524398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Directory.GetFiles: how to get only filename, not full path?
提问by Nicolas Raoul
Possible Duplicate:
How to get only filenames within a directory using c#?
可能的重复:
如何使用 c# 仅获取目录中的文件名?
Using C#, I want to get the list of files in a folder.
My goal: ["file1.txt", "file2.txt"]
使用 C#,我想获取文件夹中的文件列表。
我的目标:["file1.txt", "file2.txt"]
So I wrote this:
所以我写了这个:
string[] files = Directory.GetFiles(dir);
Unfortunately, I get this output: ["C:\\dir\\file1.txt", "C:\\dir\\file2.txt"]
不幸的是,我得到了这个输出: ["C:\\dir\\file1.txt", "C:\\dir\\file2.txt"]
I could strip the unwanted "C:\dir\" part afterward, but is there a more elegant solution?
之后我可以去掉不需要的 "C:\dir\" 部分,但是有更优雅的解决方案吗?
采纳答案by RedFilter
You can use System.IO.Path.GetFileNameto do this.
您可以使用它System.IO.Path.GetFileName来执行此操作。
E.g.,
例如,
string[] files = Directory.GetFiles(dir);
foreach(string file in files)
Console.WriteLine(Path.GetFileName(file));
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 GetFilesunless you need the additional functionality of the FileInfoclass.
虽然您可以使用FileInfo,但它比您已经使用的方法(仅检索文件路径)要重量级得多。所以我建议你坚持使用,GetFiles除非你需要这个FileInfo类的附加功能。
回答by Adriaan Stander
Have a look at using FileInfo.Name Property
看看使用FileInfo.Name 属性
something like
就像是
string[] files = Directory.GetFiles(dir);
for (int iFile = 0; iFile < files.Length; iFile++)
string fn = new FileInfo(files[iFile]).Name;
Also have a look at using DirectoryInfo Classand FileInfo Class
也看看 using DirectoryInfo Class和FileInfo Class
回答by Osiris
Use this to obtain only the filename.
使用它仅获取文件名。
Path.GetFileName(files[0]);
回答by Jignesh Thakker
Try,
尝试,
string[] files = new DirectoryInfo(dir).GetFiles().Select(o => o.Name).ToArray();
Above line may throw UnauthorizedAccessException. To handle this check out below link
上面的行可能会抛出 UnauthorizedAccessException。要处理此检查,请查看以下链接

