How to get files from exact subdirectories
Asked Answered
V

2

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
  }
}
Vitale answered 19/12, 2012 at 13:42 Comment(2)
do yo also want to exclude some directories ?Ranita
no, I want all directoriesVitale
P
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

Precaution answered 19/12, 2012 at 13:45 Comment(6)
well I tried this, but after using .Count method I'm not able to get files lenghtVitale
SelectMany is returning an IEnumerable<T>, which does not provides a Length property. You can use a simple foreach construction instead of a for loop. Check my edited codePrecaution
well after that I have problems with arrays. Do you have any suggestions? I edited/added my code.Vitale
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 foreachPrecaution
I had problem with arrays in the other part of the program, where I also used these values. Thanks for all your help!Vitale
If it can help, the method IEnumerable<T>.ToArray() can convert an enumerable to an array. You may consider the pro and cons, but it works.Precaution
U
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));
}
Unless answered 19/12, 2012 at 13:45 Comment(2)
The op wants to search in direct child subdirectories, not the root directory)Precaution
I tried your suggestion, but all I get is subdirectories lenght(number). I want files lenght, that are in subdirectoriesVitale

© 2022 - 2024 — McMap. All rights reserved.