遅い答えですが、誰かが恩恵を受けると思います。エラー処理をサポートし、相対パスを返すスタックベースの反復バージョン スターター:
private static IEnumerable<string> TryEnumerate(Func<IEnumerable<string>> action)
{
try
{
return action.Invoke();
}
catch
{
//TODO logging
return Enumerable.Empty<string>();
}
}
private static IEnumerable<string> FindFilesAndDirectories(string dir, bool returnRelativePaths = false, string filePattern="*.*")
{
var searchStack = new Stack<string>();
searchStack.Push(dir);
var initialDirectory = new DirectoryInfo(dir).FullName;
var initialDirLength = initialDirectory.Length;
while (searchStack.Count > 0)
{
var currentDirectory = searchStack.Pop();
yield return (returnRelativePaths &&
string.Compare(currentDirectory, initialDirectory, StringComparison.OrdinalIgnoreCase) != 0) ?
currentDirectory.Substring(initialDirLength) : currentDirectory;
foreach (var file in TryEnumerate(() =>
Directory.EnumerateFiles(currentDirectory, filePattern)))
{
yield return returnRelativePaths ? file.Substring(initialDirLength) : file;
}
foreach (var directory in TryEnumerate(() =>
Directory.EnumerateDirectories(currentDirectory, filePattern)))
{
searchStack.Push(directory);
}
}
}
static void Main(string[] args)
{
foreach (var result in FindFilesAndDirectories(@"c:\", true))
{
Console.WriteLine(result);
}
}