0

这就是我尝试的,但它只返回根目录下的顶级目录中的最新文件

if(Directory.Exists("YourPath"))
foreach (string _tempFiles in Directory.GetDirectories("YourPath")
                       .Select(directory => Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories)
                       .OrderByDescending(File.GetLastWriteTime)
                       .FirstOrDefault()))
4

2 回答 2

2

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

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因为错误处理很困难。

于 2013-01-20T10:35:03.200 回答
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");

于 2013-01-20T10:49:28.310 回答