Introduction
How to create a list of files in a folder and its sub-folders that were created or modified yesterday only, not today or two days ago. This is an alternative to the published version, which is over commented, making it look like student code. It should be self documenting, if you write it correctly. It's also rather ... "single use" where I much prefer a generic solution.
Using the Code
Rather than "fixing" it to "yesterday", make it generic, so you feed it a start and end date and it returns all between. That's easy to do. First, an Extension method to provide a Between
test:
public static class Extensions
{
public static bool Between(this DateTime dt, DateTime start, DateTime end)
{
if (start < end) return dt >= start && dt <= end;
return dt >= end && dt <= start;
}
}
Then, a method to use it:
public IEnumerable<FileInfo> GetFilesBetween(string path, DateTime start, DateTime end)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles();
return files.Where(f => f.CreationTime.Between(start, end) ||
f.LastWriteTime.Between(start, end));
}
To include subdirectories, use the GetFiles
overload:
FileInfo[] files = di.GetFiles("*.*", SearchOption.AllDirectories);
Then the specific "yesterday" case becomes trivial:
public IEnumerable<FileInfo> GetYesterdayFiles(string path)
{
DateTime today = DateTime.Today;
return GetFilesBetween(path, today.AddDays(-1), today);
}
History
- 2019-04-27 V1.2 Forgot to update history when published V1.1 ...
- 2019-04-27 V1.1 Typo: I typed "wheer" for "where"
- 2019-04-27 Original version. I tried suggesting this to the OP in moderation, but ...