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

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;

posted on 2015-01-14 17:12  浮沉魅影  阅读(150)  评论(0编辑  收藏  举报

导航