I want to find and add all the file names in a specific directory and all its sub-directories and add them to a list in C#. I have tried using DirectoryInfo but it only gives back files in current directory and not inside its sub-folders. Any simple method for implementing this?
Asked
Active
Viewed 8,430 times
2 Answers
2
SearchOption.AllDirectories
might do the trick for you as it includes the current directory and all its subdirectories in a search operation. This option includes reparse points such as mounted drives and symbolic links in the search.
//Add System.IO then
String[] allfiles = Directory.GetFiles("DirectorytoSearch", "*", SearchOption.AllDirectories);
and to convert them to list
List<string> allfiles = Directory.GetFiles("DirectorytoSearch", "*",SearchOption.AllDirectories).ToList();

sujith karivelil
- 28,671
- 6
- 55
- 88

Mohit S
- 13,723
- 6
- 34
- 69
-
1Better put `*` as a wild card instead of `*.*` (what if a file doesn't have extension?) – Dmitry Bychenko Dec 16 '16 at 07:18
-
-
Directory.GetFiles() returns a string[] which does not have a .ToList() option. – Pul_P Dec 16 '16 at 07:40
-
@Pul_P: You can either choose line 1 or line 2. ToList() could be done to any array object. and same here – Mohit S Dec 16 '16 at 07:44
-
-
-
Yes!! y not you can use [`Path.GetFileName`](http://stackoverflow.com/a/12524416/3796048) – Mohit S Dec 16 '16 at 08:17
-
"This option includes reparse points such as .... symbolic links". That is not my experience. Using this actually throws `DirectoryNotFoundException` when symbolic links are present – derekantrican Jun 17 '20 at 21:22
0
if you need to store them in the list here are the code:
string[] entries = Directory.GetFileSystemEntries(folderPath, "*", SearchOption.AllDirectories);
List<string> filesPaths = entries.ToList();
where "*" is the search criteria for example if you need only xml files listed you change it to "*.xml"

Yahya Hussein
- 8,767
- 15
- 58
- 114