How to get package name/version at runtime

delphi, delphi-xe2

Solution

A package is just a special type of dll, So you can use the `GetFileVersion` function defined in the SysUtils unit, this function returns the most significant 32 bits of the version number. so does not include the release and/or build numbers.

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

 Var
   FileVersion : Cardinal;
begin
  try
    FileVersion:=GetFileVersion('C:\Bar\Foo.bpl');
    Writeln(Format('%d.%d',[FileVersion shr 16, FileVersion and $FFFF]));
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

If you want retrieve the full version number (with release and build numbers included) you can use the `GetFileVersionInfoSize`, `VerQueryValue` and `GetFileVersionInfo` WinApi functions.

function GetFileVersionStr(const AFileName: string): string;
var
  FileName: string;
  LinfoSize: DWORD;
  lpdwHandle: DWORD;
  lpData: Pointer;
  lplpBuffer: PVSFixedFileInfo;
  puLen: DWORD;
begin
  Result := '';
  FileName := AFileName;
  UniqueString(FileName);
  LinfoSize := GetFileVersionInfoSize(PChar(FileName), lpdwHandle);
  if LinfoSize <> 0 then
  begin
    GetMem(lpData, LinfoSize);
    try
      if GetFileVersionInfo(PChar(FileName), lpdwHandle, LinfoSize, lpData) then
        if VerQueryValue(lpData, '\', Pointer(lplpBuffer), puLen) then
          Result := Format('%d.%d.%d.%d', [
            HiWord(lplpBuffer.dwFileVersionMS),
            LoWord(lplpBuffer.dwFileVersionMS),
            HiWord(lplpBuffer.dwFileVersionLS),
            LoWord(lplpBuffer.dwFileVersionLS)]);
    finally
      FreeMem(lpData);
    end;
  end;

end;

Problem

I'm loading package at runtime via `LoadPackage()`. Let's say after load I want to check the version of the package to ensure it's the newest. How can I do that?

Original source

Related problems