0

So I have a directory where a bunch of configuration files are stored, but now I also have several sub directories which also contain config files. I had a function for collecting all configuration files per station, but now it's only collecting files in the directory, not the sub folders. old code:

    string MasterList = "ConfigsForStation1.txt";
    string dirC = "..\\config\\Station1\\";
    foreach (FileInfo fileC in dirC.GetFiles())
            {
                if(!System.IO.Path.GetExtension(fileC.FullName).EndsWith(".confg"))
                {     WriteToList(fileC,MasterList);}

    }

and now with this sub directory stuff implemented its more along these lines:

        string MasterList = ...;
        string dirC = ...;
        //collect files in sub directories substations 1 & 2
        foreach(DirectoryInfo Dx in dirC.GetDirectories())
        {   foreach(FileInfo fileC in Dx.GetFiles())
            {...}
        }
        //collect files in parent directory station 1
        foreach(FileInfo fileC in dirC.GetFiles())
        {...}

my question is: is there a cleaner way to collect files from all sub folders rather then nest a foreach inside of a foreach? and then do a third pass for the stuff in parent. It feels abit sloppy and I feel like theres some command like dirC.getAllsub() that will do so for me? just looking for hints and ideas to clean up the code.

Medic3000
  • 786
  • 4
  • 20
  • 44

5 Answers5

2

There's Directory.EnumerateFiles() to which you can pass a parameter of SearchOption.AllDirectories which you can use to tell it to recurse the files for you automatically.

You should be able to do something like:

foreach (string filename in Directory.EnumerateFiles(dirC, "*.confg", SearchOption.AllDirectories))
    ... Do something with filename

Or if you need to process every file:

foreach (string filename in Directory.EnumerateFiles(dirC, "*", SearchOption.AllDirectories))
    ... Do something with filename
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
1

Use Directory.GetFiles() with SearchOption.AllDirectories. That will automatically recurse for you.

Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
1

I wanted to write this as a comment but stackoverflow wasn't letting me.

Check out this question which provides many ways to do what you're asking.

Community
  • 1
  • 1
1

use Directory.GetFiles:

var files = Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories);
Reacher Gilt
  • 1,813
  • 12
  • 26
1

The GetFiles() method will return them all in one shot:

String dirC = "..\\config\\Station1\\";
DirectoryInfo di = new DirectoryInfo(dirC);
FileInfo[] fia = di.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo fi in fia)
{
    //do something with the file
}

You can replace the search pattern *.* with whatever fits the files you are looking for, such as *.cfg.

DonBoitnott
  • 10,787
  • 6
  • 49
  • 68