Если кому то интересно вот решение
public IEnumerable<string> SafeEnumerateFiles(string path, string searchPattern, SearchOption searchOption)
{
Stack<string> dirs = new Stack<string>();
dirs.Push(path);
while (dirs.Count > 0)
{
string currentDirPath = dirs.Pop();
if (searchOption == SearchOption.AllDirectories)
{
try
{
string[] subDirs = Directory.GetDirectories(currentDirPath);
foreach (string subDirPath in subDirs)
{
if ((File.GetAttributes(subDirPath) & (FileAttributes.Hidden | FileAttributes.System)) != (FileAttributes.Hidden | FileAttributes.System))
{
dirs.Push(subDirPath);
}
}
}
catch (UnauthorizedAccessException)
{
continue;
}
catch (DirectoryNotFoundException)
{
continue;
}
}
string[] files = null;
try
{
files = Directory.GetFiles(currentDirPath, searchPattern);
}
catch (UnauthorizedAccessException)
{
continue;
}
catch (DirectoryNotFoundException)
{
continue;
}
foreach (string filePath in files)
{
yield return filePath;
}
}
}