-1

我需要从我的根文件夹下的每个文件夹中找到最近创建的文件。以下代码返回根文件夹中的所有文件:

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>();
        }
    }
}
4

1 回答 1

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);
}

此代码仅检查根文件夹中的文件夹

于 2013-01-17T15:06:27.603 回答