Skip to content

Instantly share code, notes, and snippets.

@tormaroe
Last active February 13, 2019 14:33
Show Gist options
  • Save tormaroe/934d6208467d73fadaa84b44b3edf5a3 to your computer and use it in GitHub Desktop.
Save tormaroe/934d6208467d73fadaa84b44b3edf5a3 to your computer and use it in GitHub Desktop.
Example code C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment