Delphi:删除超过 X 天和/或具有特殊文件掩码 (*.xxx) 的目录中的文件

Mic*_*ter 2 delphi datetime wildcard delete-file

语言: Delphi 10.1 Berlin

问题:
有一个包含测量文件 ( *.csv) 和其他文件的目录。
每隔几个小时就会创建一个新的测量文件。
我需要有可能删除.csv该文件夹中超过特定​​天数的所有文件。不应触及所有其他文件类型。

问题:
Delphi 中是否有任何内置函数来完成这项工作?如果没有,解决这个问题的有效方法是什么?

Mic*_*ter 6

我没有找到针对该特定问题的 Delphi 内置函数。
这个功能对我有用:

function TUtilities.DeleteFilesOlderThanXDays(
    Path: string;
    DaysOld: integer = 0; // 0 => Delete every file, ignoring the file age
    FileMask: string = '*.*'): integer;
var
  iFindResult : integer;
  SearchRecord : tSearchRec;
  iFilesDeleted: integer;
begin
  iFilesDeleted := 0;
  iFindResult := FindFirst(TPath.Combine(Path, FileMask), faAnyFile, SearchRecord);
  if iFindResult = 0 then begin
    while iFindResult = 0 do begin
      if ((SearchRecord.Attr and faDirectory) = 0) then begin
        if (FileDateToDateTime(SearchRecord.Time) < Now - DaysOld) or (DaysOld = 0) then begin
          DeleteFile(TPath.Combine(Path, SearchRecord.Name));
          iFilesDeleted := iFilesDeleted + 1;
        end;
      end;
      iFindResult := FindNext(SearchRecord);
    end;
    FindClose(SearchRecord);
  end;
  Result := iFilesDeleted;
end;
Run Code Online (Sandbox Code Playgroud)