递归扫描根目录下的所有目录,只查找每个文件夹中的最新文件

时间:2013-01-20 10:15:29

标签: c#

这就是我尝试但它只从根

下的顶级目录返回最新文件
if(Directory.Exists("YourPath"))
foreach (string _tempFiles in Directory.GetDirectories("YourPath")
                       .Select(directory => Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories)
                       .OrderByDescending(File.GetLastWriteTime)
                       .FirstOrDefault()))

2 个答案:

答案 0 :(得分:2)

这将返回每个目录(包括root)的所有最新文件:

var rootDirFile = Directory
    .EnumerateFiles(yourPath, "*.*", SearchOption.TopDirectoryOnly)
    .OrderByDescending(f => File.GetLastWriteTime(f))
    .Take(1);
var allNewestFilesOfEachFolder = Directory
    .EnumerateDirectories(yourParth, "*.*", SearchOption.AllDirectories)
    .Select(d => Directory.EnumerateFiles(d, "*.*")
        .OrderByDescending(f => File.GetLastWriteTime(f))
        .FirstOrDefault());
// put both together, the root-file first
allNewestFilesOfEachFolder = rootDirFile.Concat(allNewestFilesOfEachFolder);

如果目录中没有文件,则文件为null,因此文件数等于文件夹数。

请注意,Linq不是System.IO的正确工具,因为错误处理很困难。

答案 1 :(得分:0)

我写了一个基本的递归函数来处理这个问题:

// Dictionary: 
//   Key = The directory name.
//   Value = The most recently modified file for that directory.
public static Dictionary<string, string> GetNewestFiles(string directory)
{
  return GetNewestFiles(directory, null);
}

static Dictionary<string, string> GetNewestFiles(string directory, 
                                                 Dictionary<string, string> dictionary)
{
  if(dictionary == null)
    dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

  try
  {
    var files = from file in Directory.GetFiles(directory)
                select new FileInfo(file);

    var latestFile = files.OrderByDescending(file => { return file.LastWriteTimeUtc; }).FirstOrDefault();

    if (latestFile != null)
      dictionary[latestFile.DirectoryName] = latestFile.FullName;
  }
  catch { }

  foreach (var subDirectory in Directory.GetDirectories(directory))
  {
    try
    {
      GetNewestFiles(subDirectory, dictionary);
    }
    catch { }
  }

  return dictionary;
}

那么你可以这样称呼它:

var fileDictionary = GetNewestFiles(@"C:\MyFolder");