I have a folder with 198 files, among them there are 25 files with last writing date of 06.22.2014. I'm trying to get this set of last modified files, using the following code:
public static IEnumerable<FileInfo> GetLatestFiles(string path)
{
return new DirectoryInfo(path)
.GetFiles("*.log")
.GroupBy(f => f.Extension)
.Select(g => g.OrderByDescending(f => f.LastWriteTime
.Date
.ToShortDateString())
.First());
}
However, it returns me only one file, because it checks also last time modification, despite I crop the date. Is there any approach to enumerate this list of files excluding time?
It's easier to tell what you're doing if you don't just align on dots, but on top-level calls:
public static IEnumerable<FileInfo> GetLatestFiles(string path)
{
return new DirectoryInfo(path)
.GetFiles("*.log")
.GroupBy(f => f.Extension)
.Select(g => g.OrderByDescending(f => f.LastWriteTime
.Date
.ToShortDateString())
.First());
}
Now it's more obvious that you're doing a string-based ordering. Unless you happen to be in a culture which puts the year first, then the month, then the day, that's almost certainly not what you want. You probably don't care about the string representation at all. Always avoid converting to a string unless you're really interested in a textual representation.
Next, you're doing a couple of odd things:
I suspect you really want to group by date, and return everything in the most recent group. For example:
public static IEnumerable<FileInfo> GetLatestFiles(string path)
{
return new DirectoryInfo(path)
.GetFiles("*.log")
.GroupBy(f => f.LastWriteTime.Date)
.OrderByDescending(g => g.Key) // Order the groups by date (desc)
.First(); // Just return the most recent group
}
(Note that this will fail if there are no files in the directory... what do you want it to do in this case?)
You should also consider what time zone you're interested in - two files may have the same last-modified date in one time zone, but not in another...
See more on this question at Stackoverflow