You will have to skip the directories you can't read (assuming that you can't run your program under the System account or other account with privileges to read all directories).
You have to be careful here because you can't use yield
inside a try/catch
. Here's one approach:
public static IEnumerable<string> EnumFilesRecursively(string rootDirectory)
{
// Helper method to call GetEnumerator(), returning null on exception.
IEnumerator<T> getEnumerator<T>(Func<IEnumerable<T>> getEnumerable)
{
try { return getEnumerable().GetEnumerator(); }
catch { return null; }
}
// Enumerate all files in the current root directory.
using (var enumerator = getEnumerator(() => Directory.EnumerateFiles(rootDirectory)))
{
if (enumerator != null)
while (enumerator.MoveNext())
yield return enumerator.Current;
}
// Recursively enumerate all subdirectories.
using (var enumerator = getEnumerator(() => Directory.EnumerateDirectories(rootDirectory)))
{
if (enumerator != null)
while (enumerator.MoveNext())
foreach (var file in EnumFilesRecursively(enumerator.Current))
yield return file;
}
}
To test it:
public static void Main(string[] args)
{
foreach (var file in EnumFilesRecursively(@"C:\Program Files\"))
{
Console.WriteLine(file);
}
}