1

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?

Pul_P
  • 80
  • 1
  • 10

2 Answers2

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
  • 27,818
  • 6
  • 51
  • 82
Mohit S
  • 13,378
  • 5
  • 32
  • 66
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,170
  • 15
  • 53
  • 100