I have a directory with many Excel files named [MMM yyyy].xlsx:
Jan 2012.xlsx
Feb 2012.xlsx
...... etc...
May 2022.xlsx
I have the the following code that must be adjusted to sort by natural date order, rather than file write time:
Dim dir = New System.IO.DirectoryInfo(MY_PATH).GetFiles("*.xlsx",
IO.SearchOption.TopDirectoryOnly).OrderBy(Function(x) x.LastWriteTime).Reverse
For Each f As System.IO.FileInfo In dir
//code
Next
Thank you
CodePudding user response:
You can do this:
Dim dir = New DirectoryInfo(MY_PATH).
EnumerateFiles("*.xlsx", SearchOption.TopDirectoryOnly).
OrderByDescending(Function(x) DateTime.ParseExact(x.Name.Replace(".xlsx", ""), "MMM yyyy", Nothing)
For Each f As FileInfo In dir
' code
Next
Or this if you only need file names inside the loop, which might be a little faster:
Dim dir = New Directory(MY_PATH).
EnumerateFiles("*.xlsx", SearchOption.TopDirectoryOnly).
OrderByDescending(Function(x) DateTime.ParseExact(Path.GetFileNameWithoutExtension(x), "MMM yyyy", Nothing)
For Each f As String In dir
' code
Next