2

I want to access a folder through my C# code,and open up the 2nd most recently updated/created file. This is because the most recent file is always being used by a different process, so I cannot access it properly.

I have found code to find the most recent file, and it is:

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

I am unsure of how to edit it in order to find the file I am looking for. I know it'll probably be the one after the first one in descending order, but I have no idea how to access it.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Clicksurfer
  • 126
  • 10
  • If you need more options - https://www.bing.com/search?q=c%23+linq+take+second+item. Note that in general (non-IO-bound) case you may be better of not sorting but *selecting* item (O(n log n) for sorting vs. O(n) for selecting). – Alexei Levenkov Nov 10 '15 at 17:58

1 Answers1

8

You are in the right way, you just need to Skip one time to get the specified file :

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

This assumes you have at least two files in directory.

Perfect28
  • 11,089
  • 3
  • 25
  • 45