Recursively find the most recent file from each folder in folder hierarchy.
<p>I need to find the most recently created file from each folder under my root folder.
The following code returns all the files from the root folder:</p>

<pre><code>list&lt;string&gt; capturesList = SafeFileEnumerator.EnumerateFiles(pathToSearch, "*.pcap", SearchOption.AllDirectories).ToList();
</code></pre>

<p>The class <code>SafeFileEnumerator</code> searches only the location with permissions:</p>

<pre><code>public static class SafeFileEnumerator
{
    public static IEnumerable&lt;string&gt; EnumerateDirectories(string parentDirectory, string searchPattern, SearchOption searchOpt)
    {
        try
        {
            var directories = Enumerable.Empty&lt;string&gt;();
            if (searchOpt == SearchOption.AllDirectories)
            {
                directories = Directory.EnumerateDirectories(parentDirectory).SelectMany(x =&gt; EnumerateDirectories(x, searchPattern, searchOpt));
            }
            return directories.Concat(Directory.EnumerateDirectories(parentDirectory, searchPattern));
        }
        catch (UnauthorizedAccessException)
        {
            return Enumerable.Empty&lt;string&gt;();
        }
    }

    public static IEnumerable&lt;string&gt; EnumerateFiles(string path, string searchPattern, SearchOption searchOpt)
    {
        try
        {
            var dirFiles = Enumerable.Empty&lt;string&gt;();
            if (searchOpt == SearchOption.AllDirectories)
            {
                dirFiles = Directory.EnumerateDirectories(path).SelectMany(x =&gt; EnumerateFiles(x, searchPattern, searchOpt));
            }

            return dirFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
        }
        catch (UnauthorizedAccessException)
        {
            return Enumerable.Empty&lt;string&gt;();
        }
    }
}
</code></pre>
