// 删除过期文件
// AMaskedNames 表示文件名,带 * 和 ? 通配符
function DeleteExcessFiles(const ARemainNum: Integer;const APath: string;
  const AMaskedNames: array of string): Integer;
var
  sr:TSearchRec;
  sPath:String;
  slFiles:TStringList;
  i: Integer;
begin
  Result := 0;
  sPath := APath;
  if (ARemainNum > 0) and (sPath <> '' ) and DirectoryExists(sPath) then
  begin
    sPath := IncludeTrailingPathDelimiter(sPath);
    slFiles := TStringList.Create;
    try
      slFiles.Sorted := true;
      if FindFirst(sPath + '*.*',faAnyFile,sr) = 0 then
      begin
        repeat
          if (sr.Name = '.') or (sr.Name = '..') then
            continue;
          if (sr.Attr and faDirectory) <> faDirectory then // 仅文件
          begin
            for i := 0 to High(AMaskedNames) do
            begin
              if Masks.MatchesMask(sr.Name,AMaskedNames[i]) then
              begin
                slFiles.Add(Format('%d=%s',[sr.Time,sPath + sr.Name]));
                Inc(Result);
                Break;
              end;
            end;  
          end;
        until FindNext(sr) <> 0;
        SysUtils.FindClose(sr);
      end;
      // 删除保留数量外的文件(按时间倒序)
      while slFiles.Count > ARemainNum do
      begin
        SysUtils.DeleteFile(slFiles.ValueFromIndex[0]);
        slFiles.Delete(0);
      end;
    finally
      slFiles.Free;
    end;
  end;
end;