You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么Delphi的FileAge函数返回不符合预期的异常数值?

问题根因与修复方案
  • 核心故障点:FileAge函数返回值类型误用
    Delphi中FileAge默认返回DOS格式的整数时间戳,而DaysBetween要求传入TDateTime类型的参数。你直接将整数时间戳传入计算,会导致类型隐式转换出错,最终得到异常偏大的间隔天数。修复时需要先调用FileDateToDateTime将FileAge的返回值转为TDateTime类型再计算间隔。
  • 潜在问题1:循环边界越界
    你代码中删除文件的循环写为for i := 0 to sl.count do,字符串列表的索引范围是0 到 sl.count - 1,超出范围的访问会触发内存错误,需要修正边界值。
  • 潜在问题2:异常被静默吞掉
    空的except块会隐藏所有运行时错误,比如文件被占用删除失败、路径权限不足等问题都无法感知,建议添加日志记录异常信息方便排查。
  • 兼容优化建议:如果后续仍出现共享文件夹时间读取异常,可以替换FileAge为Windows API FindFirstFile直接读取文件时间属性,规避VCL控件封装带来的兼容问题。
修正后核心代码片段
function TForm1.deleteOldDownloads: boolean;
var
  f: string;
  i, d: Integer;
  sl: tstringlist;
begin
try
  FileListBox1.Directory := '\\psf\home\downloads';
  FileListBox1.refresh;
  sl := tstringlist.create;
  for i := 0 to FileListBox1.items.count - 1 do
  begin
    f := FileListBox1.Directory + '\' + FileListBox1.items[i];
    if fileexists(f) then
      // 新增FileDateToDateTime转换
      d := daysbetween(FileDateToDateTime(FileAge(f)), now)
    else
      d := 0;
    if d > 30 then
      sl.Add(f);
  end;
  if sl.count > 0 then
  begin
    // 修正循环边界为count-1
    for i := 0 to sl.count - 1 do
    begin
      f := sl[i];
      deletefile(f);
    end;
  end;
  sl.Free;
except
  on e: Exception do
    // 可在此处添加异常日志输出
    begin     
    end;
end;

内容的提问来源于stack exchange,提问作者delphirules

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:15:04