4

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
  }
}
anzes
  • 57
  • 1
  • 1
  • 7

2 Answers2

6

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

Steve B
  • 36,818
  • 21
  • 101
  • 174
  • well I tried this, but after using .Count method I'm not able to get files lenght – anzes Dec 19 '12 at 20:07
  • `SelectMany` is returning an `IEnumerable`, which does not provides a `Length` property. You can use a simple `foreach` construction instead of a `for` loop. Check my edited code – Steve B Dec 20 '12 at 08:35
  • well after that I have problems with arrays. Do you have any suggestions? I edited/added my code. – anzes Dec 20 '12 at 11:28
  • what kind of problem do you have? And please, note there is no more array but an enumerable when using SelectMany. That's why the foreach come into play in place of the foreach – Steve B Dec 20 '12 at 13:11
  • I had problem with arrays in the other part of the program, where I also used these values. Thanks for all your help! – anzes Dec 20 '12 at 13:39
  • If it can help, the method `IEnumerable.ToArray()` can convert an enumerable to an array. You may consider the pro and cons, but it works. – Steve B Dec 20 '12 at 13:47
3

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));
}
Omar
  • 16,329
  • 10
  • 48
  • 66
  • The op wants to search in direct child subdirectories, not the root directory) – Steve B Dec 19 '12 at 13:48
  • I tried your suggestion, but all I get is subdirectories lenght(number). I want files lenght, that are in subdirectories – anzes Dec 20 '12 at 08:17