获取所有没有目录的文件[C#] [英] Get all files without directories [C#]

查看:67
本文介绍了获取所有没有目录的文件[C#]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!我有一个noobish问题。我想从特定的食物中获取所有文件。我知道这样做的唯一方法是通过以下代码行:



  string  [] GetFiles = Directory.GetFiles(DirectoryPath); 





GetFiles方法的问题是......那个我也得到了子目录。有没有办法只获取文件(例如txt,bmp,ico,launch,cp和e.t.c)?谢谢!



我尝试了什么:



我试过方法GetFiles:



string [] GetFiles = Directory.GetFiles(DirectoryPath);



问题在于它也得到了文件夹。

解决方案

Directory.GetFiles() [ ^ ]接受 SearchOption [ ^ 。仅使用 TopDirectoryOnly 作为该方法的第三个参数。



示例:

  string  path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
string [] files = Directory.GetFiles(path, *。*,SearchOption.TopDirectoryOnly);

var result = files.Select(a => Path.GetFileName(a));





返回:

 file1.xlsx 
file2.bmp
file3.docx


你应该尝试下面

  var  fileList =目录
.GetFiles( 您的目录路径 *,SearchOption.AllDirectories)
.Select(Path.GetFileName);





我相信,你知道如何从fileList对象中获取单个文件名。


Hello ! I have a noobish question. I want to get all the files from a specific dieectory. The only way i know doing this.. is by this following line of code:

string[] GetFiles = Directory.GetFiles(DirectoryPath);



The problem with GetFiles method is... that i am getting the subdirectories too. Is there a way of getting only the files(for example txt, bmp, ico, launch, cp and e.t.c) ? Thanks !

What I have tried:

I have tried method GetFiles:

string[] GetFiles = Directory.GetFiles(DirectoryPath);

The problem is that it gets the folder too.

解决方案

Directory.GetFiles()[^] accepts SearchOption[^]. Use TopDirectoryOnly only as a third parameter to that method.

Example:

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string[] files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);

var result = files.Select(a=>Path.GetFileName(a));



Returns:

file1.xlsx
file2.bmp
file3.docx


You should try below

var fileList= Directory
                .GetFiles("Your directory path", "*", SearchOption.AllDirectories)
                .Select(Path.GetFileName);



I am sure, you know how to get the individual file names from the fileList object.


这篇关于获取所有没有目录的文件[C#]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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