Delphi获取文件版本号并格式化输出

方法来源于网络,谨记之并分享之,共两个函数,区别如下:

  1. GetFileVersionString :仅获取文件的版本号;
  2. GetFileVersionStringEx:获取文件版本号和版本类型(测试版?预发布版?)

演示结果如下:


代码如下:

function GetFileVersionString(const AFileName: String): String;
var
  FileName: string;
  InfoSize, Wnd: DWORD;
  VerBuf: Pointer;
  FI: PVSFixedFileInfo;
  VerSize: DWORD;
begin
  Result := '';
  FileName := AFileName;
  UniqueString(FileName);
  InfoSize := GetFileVersionInfoSize(PChar(FileName), Wnd);
  if InfoSize <> 0 then
  begin
    GetMem(VerBuf, InfoSize);
    try
      if GetFileVersionInfo(PChar(FileName), Wnd, InfoSize, VerBuf) then
        if VerQueryValue(VerBuf, '\', Pointer(FI), VerSize) then
        begin
          Result:= InttoStr(FI.dwFileVersionMS div $10000)+'.'
            +IntToStr(FI.dwFileVersionMS mod $10000)+'.'
            +IntToStr(FI.dwFileVersionLS div $10000)+'.'
            +IntToStr(FI.dwFileVersionLS mod $10000);
        end;
    finally
      FreeMem(VerBuf);
    end;
  end;
end;
function GetFileVersionStringEx(const AFileName: String): string;
var
  FileName: string;
  InfoSize, Wnd: DWORD;
  VerBuf: Pointer;
  FI: PVSFixedFileInfo;
  VerSize: DWORD;
begin
  Result := '';
  FileName := AFileName;
  UniqueString(FileName);
  InfoSize := GetFileVersionInfoSize(PChar(FileName), Wnd);
  if InfoSize <> 0 then
  begin
    GetMem(VerBuf, InfoSize);
    try
      if GetFileVersionInfo(PChar(FileName), Wnd, InfoSize, VerBuf) then
        if VerQueryValue(VerBuf, '\', Pointer(FI), VerSize) then
        begin
          Result:= InttoStr(FI.dwFileVersionMS div $10000)+'.'
            +IntToStr(FI.dwFileVersionMS mod $10000)+'.'
            +IntToStr(FI.dwFileVersionLS div $10000)+'.'
            +IntToStr(FI.dwFileVersionLS mod $10000);
          if ((FI.dwFileFlags and VS_FF_DEBUG) xor VS_FF_DEBUG)=0 then
            Result:=Result+' Debug Version.';
          if ((FI.dwFileFlags and VS_FF_PRERELEASE) xor VS_FF_PRERELEASE)=0 then
            Result:=Result+' Trial Version.';
        end;
    finally
      FreeMem(VerBuf);
    end;
  end;
end;
有人爱: 醉倚黄昏
有事做: https://zyhh.me/delphi/getfileversion.html
有所期待: 一个有雨有肉的夜晚,和你没头没尾分一瓶酒。