Skip to content

Instantly share code, notes, and snippets.

@JeffJacobson
Created February 27, 2015 01:40
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 JeffJacobson/fdfd8512e585490ac218 to your computer and use it in GitHub Desktop.
Save JeffJacobson/fdfd8512e585490ac218 to your computer and use it in GitHub Desktop.
Utilities for walking through file systems
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
public static class FileSystemExtensions
{
/// <summary>
/// Walks the file system, similar to Python's os.walk function.
/// </summary>
/// <param name="root">The root directory where the walking starts.</param>
/// <param name="handler">A function that will be invoked for each directory.</param>
/// <param name="searchRegex">A regular expression used to filter the list of files. If a value is provided, <paramref name="searchPattern"/> will be ignored.</param>
/// <param name="searchPattern">The search pattern used to limit the files and directories.</param>
/// <param name="searchOption">Option to use when searching files and directories.</param>
/// <param name="searchPatternAppliesToDirectories">Determines if the <paramref name="searchPattern"/> and <paramref name="searchOption"/> are used on only the files or both the files and directories.</param>
/// <example><code>static void AddToFileList(DirectoryInfo root, DirectoryInfo[] directories, FileInfo[] files)
/// {
/// foreach (var file in files)
/// {
/// Console.WriteLine(file.FullName);
/// }
/// }
///
/// static void Main(string[] args)
/// {
/// var root = new DirectoryInfo(@"C:\temp");
/// root.Walk(AddToFileList);
/// }</code></example>
public static void Walk(this DirectoryInfo root, Action<DirectoryInfo, IEnumerable<DirectoryInfo>, IEnumerable<FileInfo>> handler, Regex searchRegex = null,
string searchPattern = null, SearchOption searchOption = SearchOption.AllDirectories, bool searchPatternAppliesToDirectories = false)
{
if (root == null)
{
throw new ArgumentNullException("directory");
}
IEnumerable<DirectoryInfo> directories = !searchPatternAppliesToDirectories || (searchRegex != null && searchPattern == null) ? root.EnumerateDirectories()
: searchRegex != null ? root.EnumerateDirectories().Where(d => searchRegex.IsMatch(d.Name))
: root.GetDirectories(searchPattern, searchOption);
IEnumerable<FileInfo> files = searchRegex == null && searchPattern == null ? root.GetFiles()
: searchRegex != null ? root.EnumerateFiles().Where(f => searchRegex.IsMatch(f.Name))
: root.GetFiles(searchPattern, searchOption);
handler.Invoke(root, directories, files);
foreach (var d in directories)
{
d.Walk(handler, searchRegex, searchPattern, searchOption);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment