Find Last Month File in Directory


I’m trying to find the last month file in a specific directory by using the modified date. I am currently able to get the latest file in the directory with this snippet: Directory.EnumerateFiles(JsonConfigOut(“NetworkDrive”).ToString(),JsonConfigOut(“ProjectIDInputFile”).ToString,SearchOption.TopDirectoryOnly).OrderByDescending(Function(x) New FileInfo(x).CreationTime).Take(1)

However, is there a way to get the file with the latest modified date from the previous month? For example, if I ran the script today (10/23), I would like to grab the file with the modified date of 9/30. Thanks!


There are a few approaches you could take.
What if you just filter out the dates that’s greater than or equal to last file?
You can simply add a .Where()
Also let’s assume you store the latest file to a variable, we can call lastFile, so we can look at the write time of that file to compare

Directory.EnumerateFiles(JsonConfigOut(“NetworkDrive”).ToString(),JsonConfigOut(“ProjectIDInputFile”).ToString,SearchOption.TopDirectoryOnly).OrderByDescending(Function(x) New FileInfo(x).CreationTime).Where(Function(x) New FileInfo(x).LastWriteTime.Month < New FileInfo(lastFile).LastWriteTime.Month And New FileInfo(x).LastWriteTime.Year <= New FileInfo(lastFile).LastWriteTime.Year ).Take(1)

You can place the .Where() before or after the OrderByDescending.

Hope that helps. —I did not test my example to confirm, cause short of time.


Thanks for that. I will take a stab at it.