I want to get the name of the newest file in a folder by using TDirectory.GetFiles in code. This is what I tried, but this doesn't always return the newest file's name because the predicate function doesn't get called in timestamp sequence.
var
FLastTime: TDateTime;
searchResults: TArray<String>;
begin
FlastTime := 0;
FPollDir := 'c:\tempfiles';
FFileExt := '*.xlsx';
searchResults := TDirectory.GetFiles(FPollDir, FFileExt,
TSearchOption.soTopDirectoryOnly,
function(const Path: String; const SearchRec: TSearchRec): Boolean
begin
if (SearchRec.TimeStamp > FLastTime) then
begin
FLastTime := SearchRec.TimeStamp;
Result := True;
end;
end);
Is it possible to do this using TDirectory
, or should I use FindFirst
rather?
You need to remember the name of the newest file found so far. Do that using a simple variable.
Also, you can let the predicate function return False, which means "don't include the current file in the search results". This does not affect the end result, but saves a bit of memory while your program is running. You don't need the search results (the array of all files), because you're interested in only ONE file -- the newest one.
The code would look like this:
var
FLastTime: TDateTime;
searchResults: TArray<String>;
FNewestFile: string;
begin
FlastTime := 0;
FPollDir := 'c:\tempfiles';
FFileExt := '*.xlsx';
searchResults := TDirectory.GetFiles(FPollDir, FFileExt,
TSearchOption.soTopDirectoryOnly,
function(const Path: String; const SearchRec: TSearchRec): Boolean
begin
if (SearchRec.TimeStamp > FLastTime) then
begin
FLastTime := SearchRec.TimeStamp;
FNewestFile := SearchRec.Name;
end;
Result := False;
end);