skip to main | skip to sidebar

26 October 2009

Better FileFolder Recursion Algorithm – More Code Friendly

I’d like you to read the code first

static class FileHelper
{
public static List<string> GetFilesRecursive(string b)
{
// 1.
// Store results in the file results list.
List<string> result = new List<string>();

// 2.
// Store a stack of our directories.
Stack<string> stack = new Stack<string>();

// 3.
// Add initial directory.
stack.Push(b);

// 4.
// Continue while there are directories to process
while (stack.Count > 0)
{
// A.
// Get top directory
string dir = stack.Pop();

try
{
// B
// Add all files at this directory to the result List.
result.AddRange(Directory.GetFiles(dir, "*.*"));

// C
// Add all directories at this directory.
foreach (string dn in Directory.GetDirectories(dir))
{
stack.Push(dn);
}
}
catch
{
// D
// Could not open the directory
}
}
return result;
}
}

what do you think? I like the idea of Pop Push method to use in recursion instead of method recursion..

read the full article here

C# Recursive File and Directory Method

0 comments: