我需要从我的根文件夹下的每个文件夹中找到最近创建的文件。以下代码返回根文件夹中的所有文件:
list<string> capturesList = SafeFileEnumerator.EnumerateFiles(pathToSearch, "*.pcap", SearchOption.AllDirectories).ToList();
该类SafeFileEnumerator
仅搜索具有权限的位置:
public static class SafeFileEnumerator
{
public static IEnumerable<string> EnumerateDirectories(string parentDirectory, string searchPattern, SearchOption searchOpt)
{
try
{
var directories = Enumerable.Empty<string>();
if (searchOpt == SearchOption.AllDirectories)
{
directories = Directory.EnumerateDirectories(parentDirectory).SelectMany(x => EnumerateDirectories(x, searchPattern, searchOpt));
}
return directories.Concat(Directory.EnumerateDirectories(parentDirectory, searchPattern));
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
}
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOpt)
{
try
{
var dirFiles = Enumerable.Empty<string>();
if (searchOpt == SearchOption.AllDirectories)
{
dirFiles = Directory.EnumerateDirectories(path).SelectMany(x => EnumerateFiles(x, searchPattern, searchOpt));
}
return dirFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
}
}