在论坛中搜索后,我找到了问题的解决方案:我有根文件夹,我想从根文件夹下的每个目录中找到最新的文件:
public static void FindNewestFile(string path)
{
List<string> list = getNewestFile(path);
foreach (string dir in list)
{
DirectoryInfo directory = new DirectoryInfo(dir);
try
{
FileInfo file = directory.GetFiles("*.*", SearchOption.AllDirectories).OrderByDescending(f => f.LastWriteTime).FirstOrDefault();
if (file != null)
{
// Do things with my file
}
}
catch (UnauthorizedAccessException)
{ }
}
}
private static List<string> getNewestFile(string path)
{
List<string> list = new List<string>();
foreach (string dir in EnumerateFoldersRecursively(path))
{
list.Add(dir);
}
return list;
}
private static IEnumerable<string> EnumerateFoldersRecursively(string root)
{
foreach (var folder in EnumerateFolders(root))
{
yield return folder;
foreach (var subFolder in EnumerateFoldersRecursively(folder))
{
yield return subFolder;
}
}
}
private static IEnumerable<string> EnumerateFolders(string root)
{
WIN32_FIND_DATA findData;
string spec = Path.Combine(root, "*");
using (SafeFindHandle findHandle = FindFirstFile(spec, out findData))
{
if (!findHandle.IsInvalid)
{
do
{
if ((findData.cFileName != ".") && (findData.cFileName != "..")) // Ignore special "." and ".." folders.
{
if ((findData.dwFileAttributes & FileAttributes.Directory) != 0)
{
yield return Path.Combine(root, findData.cFileName);
}
}
}
while (FindNextFile(findHandle, out findData));
}
}
}
我的问题是它绕过根目录并且不从该目录返回最新文件