【问题标题】:How to find the second latest file in folder [duplicate]如何在文件夹中找到第二个最新文件[重复]
【发布时间】:2016-02-11 16:47:07
【问题描述】:

我想通过我的 C# 代码访问一个文件夹,并打开 2nd 最近更新/创建的文件。这是因为最近的文件总是被不同的进程使用,所以我无法正常访问它。

我找到了找到最新文件的代码,它是:

var DataLogFile = (from f in directory.GetFiles()
                   orderby f.LastWriteTime descending
                   select f).First();

我不确定如何编辑它以找到我正在寻找的文件。我知道它可能会按降序排列在第一个之后,但我不知道如何访问它。

【问题讨论】:

  • 如果您需要更多选择 - bing.com/search?q=c%23+linq+take+second+item。请注意,在一般(非 IO 绑定)情况下,您可能最好不要排序,而是 选择 项(O(n log n) 用于排序,O(n) 用于选择)。跨度>

标签: c# linq file


【解决方案1】:

你的方法是对的,你只需要Skip一次就可以得到指定的文件:

 var DataLogFile = (from f in directory.GetFiles()
                           orderby f.LastWriteTime descending
                           select f).Skip(1).First();

这假设您在directory 中至少有两个文件。

【讨论】:

  • 如果目录中只有一个文件呢? (提示:抛出异常)
  • 如何更新最后 3 个文件?
猜你喜欢
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 2016-10-25
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多