In Delphi, I need to get a list of files from a directory based on date. my current code is returning all the files requested, using
Files := tDirectory.GetFiles(aDir, '*.docx', tSearchOption.soAllDirectories);
and I want those files, based on a date (so I don't have to process 20000 files, only the 10 that have been added since the 'last' time I checked...)
is there a way to do this?
You can use the following code:
USES System.Types, System.IOUtils;
FUNCTION GetFilesNewerThan(CONST Path,SearchPattern : STRING ; CONST SearchOption : TSearchOption ; CONST NewerThan : TDateTime) : TStringDynArray;
BEGIN
Result:=TDirectory.GetFiles(Path,SearchPattern,SearchOption,
FUNCTION(CONST Path : STRING ; CONST SearchRec : TSearchRec) : BOOLEAN
BEGIN
Result:=(SearchRec.TimeStamp>NewerThan)
END);
END;
This calls the TDirectory.GetFiles method but applies a filter so that only files that have a "LastWrite" time later than the given "NewerThan" parameter is returned.
It will still have to read the entire directory structure - there's no built-in way to filter on time stamps if you don't constantly monitor the directory like David suggests (I assume this is a program that is run "on demand" and not a service that runs 24/7).