using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Aurora.Utils { public class FileSystemUtils { public FileSystemUtils() { } /// /// Asynchronousely recursively traverse a directory path. /// /// The path to the directory to traverse /// Comma separated list of file extensions to accept public static List TraverseFoldersAsync(string path, string extensions) { string[] extensionList = extensions.Split(','); ConcurrentBag tasks = new ConcurrentBag(); List outFiles = new List(); DirectoryInfo directoryInfo = new DirectoryInfo(path); tasks.Add(Task.Run(() => Traverse(directoryInfo, tasks, outFiles, extensionList))); Task waitingTask; while (tasks.TryTake(out waitingTask)) { waitingTask.Wait(); } return outFiles; } /// /// Recursive method to capture children of a directory. /// /// The directory to traverse /// The list of currently running tasks private static void Traverse(DirectoryInfo dir, ConcurrentBag tasks, List outFiles, string[] extensions) { try { DirectoryInfo[] directoryInfos = dir.GetDirectories(); //Enque children foreach (DirectoryInfo childInfo in directoryInfos) { tasks.Add(Task.Run(() => Traverse(childInfo, tasks, outFiles, extensions))); } //Collect files foreach (FileInfo fileInfo in dir.GetFiles()) { if (extensions.Any(e => e == fileInfo.Extension)) { //Don't know if this lock is necessary lock (outFiles) { outFiles.Add(fileInfo); } } } } catch (Exception ex) { Console.WriteLine($"{ex.GetType()} {ex.Message}\n{ex.StackTrace}"); ex = ex.InnerException; } } } }