如何在运行时检索存储在Windows EXE / DLL中的版本信息? 此信息是使用资源文件手动设置的。
下面是使用标准Windows API函数的C ++方法:
try { TCHAR szFileName[ MAX_PATH ]; if( !::GetmoduleeFileName( 0, szFileName, MAX_PATH ) ) throw __LINE__; DWORD nParam; DWORD nVersionSize = ::GetFileVersionInfoSize( szFileName, &nParam ); if( !nVersionSize ) throw __LINE__; HANDLE hMem = ::GetProcessHeap(); if( !hMem ) throw __LINE__; LPVOID lpVersionData = ::HeapAlloc( hMem, 0, nVersionSize ); if( !lpVersionData ) throw __LINE__; if( !::GetFileVersionInfo( szFileName, 0, nVersionSize, lpVersionData ) ) throw __LINE__; LPVOID pVersionInfo; UINT nSize; if( !::VerQueryValue( lpVersionData, _T("\\"), &pVersionInfo, &nSize ) ) throw __LINE__; VS_FIXEDFILEINFO *pVSInfo = (VS_FIXEDFILEINFO *)pVersionInfo; CString strVersion; strVersion.Format( _T(" version %i.%i.%i.%i"), pVSInfo->dwProductVersionMS >> 16, pVSInfo->dwProductVersionMS & 0xFFFF, pVSInfo->dwProductVersionLS >> 16, pVSInfo->dwProductVersionLS & 0xFFFF ); GetDlgItem( IDC_ABOUT_VERSION )->SetWindowText( strAppName + strVersion ); if( !HeapFree( hMem, 0, lpVersionData ) ) throw __LINE__; } catch( int err ) { ASSERT( !err ); // always break on debug builds to inspect error codes and such DWORD dwErr = ::GetLastError(); // handle memory cleanup... }
请注意, catch部分是纯粹的教育 – 在实际情况下,你会妥善清理内存分配后,实际使用错误代码!
瓦伦丁的答案是正确的,但请注意评论者对可能发生内存泄露的警告。
我也不确定为什么你会在这个时代使用:: HeapAlloc。
这里是一个片段,使用新的和boost :: shared_array做什么,恕我直言,是一种更安全,更干净的方式相同的事情。
#include <boost/shared_array.hpp> //..... DWORD dwHandle; DWORD dwFileVersionInfoSize = GetFileVersionInfoSize((LPTSTR)lpszFileName, &dwHandle); if (!dwFileVersionInfoSize) return FALSE; // ensure our data will be deleted boost::shared_array<BYTE> data(new BYTE[dwFileVersionInfoSize]); LPVOID const lpData = data.get(); //party on with lpData....
这是一个Delphi 7版本:
uses Windows, SysUtils; function GetEXEVersion(exename: string; const Fmt : string = '%d.%d.%d.%d'): string; { credit to martinstoeckli@gmx.ch ( http://martinstoeckli.ch/delphi/delphi.html#AppVersion ) } var iBufferSize, iDummy : dword; pBuffer, pFileInfo : Pointer; iVer : array[1..4] of word; begin Result := ''; iBufferSize := GetFileVersionInfoSize(PChar(exename), iDummy); if iBufferSize > 0 then begin GetMem(pBuffer, iBufferSize); try GetFileVersionInfo(PChar(exename), 0, iBufferSize, pBuffer); VerQueryValue(pBuffer, '\', pFileInfo, iDummy); iVer[1] := HiWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionMS); iVer[2] := LoWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionMS); iVer[3] := HiWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionLS); iVer[4] := LoWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionLS); finally FreeMem(pBuffer); end; Result := Format(Fmt, [iVer[1],iVer[2],iVer[3],iVer[4]] ); end; end;
检查.NET程序集,在C#中:
System.Reflection.Assembly.LoadFile(@ “C:\ WINDOWS \ Microsoft.NET \框架\ V2.0.50727 \ system.data.dll中”)。的GetName()Version.ToString();