Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining which file in a folder is the latest by "modified date"?

Tags:

delphi

I need to scan a specific folder for the latest file (basically check the modified date to see which is the newest), But keep in mind that the files have random names. Here's what I got so far:

procedure TForm1.Button1Click(Sender: TObject);
begin

ftp.Host := 'domain';
ftp.Username := 'username';
ftp.password := 'password';
ftp.Connect;
ftp.Put('random-filename.ext'); //This is where it should grab only the latest file  
ftp.Quit;
ftp.Disconnect;

end;

Is this possible?

Thank you!

like image 311
John Rosenberg Avatar asked Feb 23 '23 07:02

John Rosenberg


2 Answers

Assuming that OP wants to scan specific local folder and find the most recent modified file, here's a very simple function to do just that:

function GetLastModifiedFileName(AFolder: String; APattern: String = '*.*'): String;
var
  sr: TSearchRec;
  aTime: Integer;
begin
  Result := '';
  aTime := 0;
  if FindFirst(IncludeTrailingPathDelimiter(AFolder) + APattern, faAnyFile, sr) = 0 then
  begin
    repeat
      if sr.Time > aTime then
      begin
        aTime := sr.Time;
        Result := sr.Name;
      end;
    until FindNext(sr) <> 0;
    FindClose(sr);
  end;
end;

AFolder should be an absolute or relative path to a folder you want to scan, APattern is optional and should contain a standard DOS pattern that specifies which files should be checked. If nothing is specified for 2nd parameter, *.* (all files) is assumed. Result will be the file name that has the most recent modified date.

like image 188
LightBulb Avatar answered Mar 01 '23 23:03

LightBulb


Because i think you are trying to put the latest file from your local machine to an ftp server, you can use the shell Api function: ShGetFileInfo

Get all files from your source folder first and then get the FileInfo for every file - Keep the filename with the latest modified date in a temp. var.

See this site for example: http://www.scip.be/index.php?Page=ArticlesDelphi06&Lang=EN

like image 33
Grrbrr404 Avatar answered Mar 01 '23 23:03

Grrbrr404