How can I perform full recursive directory & file

2019-01-26 04:42发布

问题:

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 ?

回答1:

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


回答2:

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);


回答3:

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
}


回答4:

You have to use

Directory.GetFiles(targetDirectory);

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



回答5:

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
    }
}


回答6:

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, "*.*");