here is my code:
private static void TreeScan(string sDir)
{
foreach (string d in Directory.GetDirectories(sDir))
{
forea
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, "*.*");
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
}
}
You have to use
Directory.GetFiles(targetDirectory);
like in This sample, wich contains a complete implementation of what you're looking for
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
}
private static void TreeScan( string sDir )
{
foreach (string f in Directory.GetFiles( sDir ))
{
//Save f :)
}
foreach (string d in Directory.GetDirectories( sDir ))
{
TreeScan( d );
}
}
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);