Skip to content

Instantly share code, notes, and snippets.

@refactorsaurusrex
Created November 2, 2015 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save refactorsaurusrex/6d520abbac608000af37 to your computer and use it in GitHub Desktop.
Save refactorsaurusrex/6d520abbac608000af37 to your computer and use it in GitHub Desktop.
Recursively navigate the file system, skipping any files or directories that are not accessible.
public static IEnumerable<string> GetFiles(string root, string searchPattern)
{
Stack<string> pending = new Stack<string>();
pending.Push(root);
while (pending.Count != 0)
{
var path = pending.Pop();
string[] next = null;
try
{
next = Directory.GetFiles(path, searchPattern);
}
catch { }
if (next != null && next.Length != 0)
foreach (var file in next) yield return file;
try
{
next = Directory.GetDirectories(path);
foreach (var subdir in next) pending.Push(subdir);
}
catch { }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment