我需要从根文件夹下的每个文件夹中找到最近创建的文件。 以下代码返回根文件夹中的所有文件:
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>();
}
}
}
答案 0 :(得分:2)
从根文件夹下的每个文件夹中获取最近创建的文件:
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);
}
此代码仅检查根文件夹中的文件夹