15

here is my code:

    private static void TreeScan(string sDir)
    {
        foreach (string d in Directory.GetDirectories(sDir))
        {
            foreach (string f in Directory.GetFiles(d))
            {
                //Save file f
            }
        }
        TreeScan(d, client);
    }

The problem is that it doesn't get the FILES of the sDir (Starting Directory) it only gets the Folders and the Files in the Sub Folders.

How can I make it get the files from the sDir too ?

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Danpe
  • 18,668
  • 21
  • 96
  • 131

6 Answers6

49

Don't reinvent the wheel, use the overload of GetFiles that allows you to specify that it searches subdirectories.

string[] files 
    = Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories);
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
9
private static void TreeScan( string sDir )
{
    foreach (string f in Directory.GetFiles( sDir ))
    {
        //Save f :)
    }
    foreach (string d in Directory.GetDirectories( sDir ))
    {
        TreeScan( d ); 
    }
}
Danpe
  • 18,668
  • 21
  • 96
  • 131
Joel Lucsy
  • 8,520
  • 1
  • 29
  • 35
2

There are some problems with your code. For one, the reason you never saw the files from the root folder is because your recursed before doing and file reads. Try this:

public static void Main()
{
    TreeScan(@"C:\someFolder");
}

private static void TreeScan(string sDir)
{
    foreach (string f in Directory.GetFiles(sDir))
        Console.WriteLine("File: " + f); // or some other file processing

    foreach (string d in Directory.GetDirectories(sDir))
        TreeScan(d); // recursive call to get files of directory
}
Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
1

You have to use

Directory.GetFiles(targetDirectory);

like in This sample, wich contains a complete implementation of what you're looking for

james_bond
  • 6,778
  • 3
  • 28
  • 34
0

If using Fx4 and above the EnumerateFiles method will return all files with efficient memory management, whereas GetFiles can require max resources on big directories (or drives).

var files = Directory.EnumerateFiles(dir.Path, "*.*");
2Yootz
  • 3,971
  • 1
  • 36
  • 31
0

Your GetFiles loop should be outside the GetDirectories loop. And shouldn't your TreeScan stay inside GetDirectories loop? In short the code should look like this:

private static void TreeScan(string sDir)
{
    foreach (string d in Directory.GetDirectories(sDir))
    {
        TreeScan(d, client);
    }
    foreach (string f in Directory.GetFiles(d))
    {
        //Save file f
    }
}
Zekareisoujin
  • 465
  • 1
  • 5
  • 19