代码之家  ›  专栏  ›  技术社区  ›  Michael Hutter

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

  •  0
  • Michael Hutter  · 技术社区  · 6 年前

    Language: 德尔福10.1柏林

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

    问题:
    Delphi中是否有内置的功能来完成这项工作?如果不是,解决这个问题的有效方法是什么?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Michael Hutter    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;
    
        2
  •  -1
  •   Andreas    6 年前
    procedure DeleteFilesOlderThan(
      const Days: Integer;
      const Path: string;
      const SearchPattern: string = '*.*');
    var
      FileName: string;
      OlderThan: TDateTime;
    begin
      Assert(Days >= 0);
      OlderThan := Now() - Days;
      for FileName in TDirectory.GetFiles(Path, SearchPattern) do
        if TFile.GetCreationTime(FileName) < OlderThan then
          TFile.Delete(FileName);
    end;