How to get files from exact subdirectories

I managed to get the files from the "root" subdirectories, but I also get the files from these subdirectories2, which I don’t want.

Example: RootDirectory>Subdirectories (wanted files)>directories2 (unwanted files)

I used this code:

 public void ReadDirectoryContent() { var s1 = Directory.GetFiles(RootDirectory, "*", SearchOption.AllDirectories); { for (int i = 0; i <= s1.Length - 1; i++) FileInfo f = new FileInfo(s1[i]); . . . etc } } 
+4
source share
2 answers

Try the following:

 var filesInDirectSubDirs = Directory.GetDirectories(RootDirectory) .SelectMany(d=>Directory.GetFiles(d)); foreach(var file in filesInDirectSubDirs) { // Do something with the file var fi = new FileInfo(file); ProcessFile(fi); } 

The idea is to first select the 1st level of subdirectories, then β€œcollect” all the files using the Enumerable.SelectMany method

+6
source

You must change SearchOption.AllDirectories to SearchOption.TopDirectoryOnly because the first means that it gets files from the current directory and all subdirectories.

EDIT:

The operator wants to search the direct child subdirectories, and not the root directory.

 public void ReadDirectoryContent() { var subdirectories = Directory.GetDirectories(RootDirectory); List<string> files = new List<string>(); for(int i = 0; i < subdirectories.Length; i++) files.Concat(Directory.GetFiles(subdirectories[i], "*", SearchOption.TopDirectoryOnly)); } 
+3
source

All Articles