Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get files from exact subdirectories

Tags:

c#

getfiles

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
  }
}
like image 293
anzes Avatar asked Jan 15 '23 17:01

anzes


2 Answers

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

like image 135
Steve B Avatar answered Jan 21 '23 12:01

Steve B


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));
}
like image 24
Omar Avatar answered Jan 21 '23 12:01

Omar