根据文件路径检测文件大小并检测是否正在被占用

来源:互联网 发布:java开发者 编辑:程序博客网 时间:2024/05/17 16:15
function CheckFileSize(sPath: string): Int64;var  FilePath: AnsiString;  FStream:TFileStream;  bOpen:Boolean;  //判断文件FileName是否正在被打开/使用  function IsFileInUse(const FileName: string): boolean;  var    HFileRes: HFILE;  begin    if not FileExists(FileName) then    begin      Result := False;      Exit;    end;    try      HFileRes := CreateFile(pchar(FileName), GENERIC_READ,        0 {this is the trick!}, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);      Result := (HFileRes = INVALID_HANDLE_VALUE);      if not Result then        CloseHandle(HFileRes);    except      Result := true;    end;  end;begin  try    try      IsFileInUse(sPath);      if FileExists(sPath) then      begin        bOpen := false;        while not bOpen do        begin          try            IsFileInUse(sPath);            FStream := TFileStream.Create(sPath, fmOpenWrite);            bOpen := true;          except on E: Exception do            bOpen := false;          end;        end;        FStream.Position := FStream.Size;        Result := FStream.Size;      end      else      begin        FStream := TFileStream.Create(sPath, fmCreate);        Result := 0;      end;    except      on e: Exception do      begin        Result := -2;      end;    end;  finally    FreeAndNil(FStream);  end;end;

0 0
原创粉丝点击