I've managed to get files out of "root" folder subdirectories, but I also get files from these subdirectories directories2, which I don't want to.
Example: RootDirectory>Subdirectories (wanted files)>directories2 (unwanted files)
I've 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
}
}
Try this :
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 1st level of subdirectories, then "aggregate" all files using Enumerable.SelectMany method
You have to change SearchOption.AllDirectories
to SearchOption.TopDirectoryOnly
, because the first one means that it gets the files from the current directory and all the subdirectories.
EDIT:
The op wants to search in direct child subdirectories, 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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With