Friday, 1 May 2009

How to loop through all files in a folder or directory tree

The code is fairly self explanatory:

/// sourceDir = directory to scan, scanLvl = current scan level, maxLvl = how deep to scan, searchPattern files to match

public static void ProcessFiles(string sourceDir, int scanLvl, int maxLvl, string searchPattern)
if (scanLvl<=maxLvl)
string [] fileEntries = Directory.GetFiles(sourceDir, searchPattern);
foreach(string fileName in fileEntries)
// do something with file

// Recurse into subdirectories
string [] subdirEntries = Directory.GetDirectories(sourceDir);
foreach(string subdir in subdirEntries)
if ((File.GetAttributes(subdir) &
FileAttributes.ReparsePoint) !=

ProcessDir(subdir, scanLvl+1, maxLvl, searchPattern);


Thanks to Ohad for the starting point for this one.

No comments: