I'm sorting a list of files that was created from yesterday 1:00pm to present time. I'm trying to use the following code: The messagebox shows the correct time I'm trying to reference, but the filter doesn't seem to work. If I remove the "AddHours(13)" it does filter correctly.
MessageBox.Show(DateTime.Now.Date.AddDays(-1).AddHours(13).ToString()); string files = Directory.GetFiles(FBD.SelectedPath, "*.xls") .Where(file => new FileInfo(file).CreationTime.Date >= (DateTime.Now.Date.AddDays(-1).AddHours(13)) && file.Contains("AA")) .OrderBy(file => new FileInfo(file).CreationTime.Date) .ToArray();
What am I missing?
DateTime.Now.Date.AddDays(-1).AddHours(13) will return 1pm... but you're checking against
new FileInfo(file).CreationTime.Date, which is always at midnight... for a file created yesterday, it will be yesterday at midnight.
So yes, you're filtering out that file. If you remove the
.Date part from
new FileInfo(file).CreationTime that may well be all you need to do.
As a side-note, I'd use
DateTime.Today instead of
DateTime.Now.Date, and I'd also try to avoid evaluating it multiple times. I'd also use
DirectoryInfo and stick to
FileInfo entries given that you're already creating those twoce. I'd rewrite your query as something like:
var cutoff = DateTime.Today.AddDays(-1).AddHours(13); FileInfo files = new DirectoryInfo(FBD.SelectedPath).GetFiles("*.xls") .Where(file => file.CreationTime >= cutoff) .OrderBy(file => file.CreationTime) .ToArray();
See more on this question at Stackoverflow