递归地从文件夹层次结构中的每个文件夹中查找最新的文件
本文关键字:文件夹 查找 最新 文件 层次结构 递归 | 更新日期: 2023-09-27 17:53:51
我需要从根文件夹下的每个文件夹中找到最近创建的文件。下面的代码返回根文件夹中的所有文件:
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>();
}
}
}
从根文件夹下的每个文件夹中获取最近创建的文件,您可以看到:
if(Directory.Exists("YourPath"))
foreach (string _tempFiles in Directory.GetDirectories("YourPath","*", SearchOption.AllDirectories)
.Select(directory => Directory.GetFiles(directory, "*.*" )
.OrderByDescending(File.GetLastWriteTime)
.FirstOrDefault()))
{
MessageBox.Show(_tempFiles);
}
这段代码只检查根文件夹