I need to get list of all files supported by some libary (images) in specified directory and all subderictories.
Root directory of drive might be chosen and in this case I want to skip system folders like "Windows" and "AppData" (some other?).
For such task I can use Directory.GetFiles()
but problem is - it will stop after getting any exception. In this case I need to just ignore noncritical exceptions and skip folders that cause this exception.
This code looks resonable to me. But I want to make sure that it done right.
Please tell me if it should be changed somehow.
public static List<string> FindSupportedFiles(string root)
{
Queue<string> folders = new Queue<string>();
List<string> files = new List<string>();
folders.Enqueue(root);
while (folders.Count != 0)
{
string currentFolder = folders.Dequeue();
if (currentFolder.Contains(":\\Windows") ||
(currentFolder.Contains(":\\Users") &&
currentFolder.Contains("\\AppData")))
{
if (folders.Count != 0) currentFolder = folders.Dequeue();
continue;
}
string[] filesInCurrent = null;
try
{
filesInCurrent = Directory.GetFiles(currentFolder, "*.*");
}
// Ignore this exceptions
catch (UnauthorizedAccessException) { }
catch (PathTooLongException) { }
catch (DirectoryNotFoundException) { }
foreach (string f in filesInCurrent)
if (optimizer.IsSupported(f)) files.Add(f);
string[] foldersInCurrent = null;
try
{
foldersInCurrent = Directory.GetDirectories(currentFolder);
}
// Ignore this exceptions
catch (UnauthorizedAccessException) { }
catch (PathTooLongException) { }
catch (DirectoryNotFoundException) { }
foreach (string _current in foldersInCurrent)
folders.Enqueue(_current);
}
return files;
}