转载:http://langzi0115.bokee.com/6868393.html
使用GetFileVersionInfoSize(),GetFileVersionInfo()和VerQueryValue()三个API可以获得.exe和.dll文件的版本信息
1.获得自身的版本信息
//
// // File: version.cpp // Description: Sample code for getting version info // Created: 2008-1-4 // Author: Ken Zhang // E-Mail: cpp.china@hotmail.com // // /* The following code shows how to get FILEINFO value from resource file. These WIN32 functions will be used: * GetFileVersionInfo * GetFileVersionInfoSize * VerQueryValue * GetModuleFileName */ #include <windows.h> #include <tchar.h> #include <string> #include <iostream> #pragma comment(lib, "version.lib") using namespace std ; bool GetFileVersion ( HMODULE hModule , WORD * pBuffer ) { TCHAR fname [ MAX_PATH ]; VS_FIXEDFILEINFO * pVi ; DWORD dwHandle ; string str ; if (:: GetModuleFileName ( hModule , fname , MAX_PATH )) { int size = GetFileVersionInfoSize ( fname , & dwHandle ); if ( size > 0 ) { BYTE * buffer = new BYTE [ size ]; if ( GetFileVersionInfo ( fname , dwHandle , size , buffer )) { if ( VerQueryValue ( buffer , _T ( "\\"), ( LPVOID *)& pVi , ( PUINT )& size )) { pBuffer [ 0 ] = HIWORD ( pVi -> dwFileVersionMS ); pBuffer [ 1 ] = LOWORD ( pVi -> dwFileVersionMS ); pBuffer [ 2 ] = HIWORD ( pVi -> dwFileVersionLS ); pBuffer [ 3 ] = LOWORD ( pVi -> dwFileVersionLS ); delete buffer ; return true ; } } delete buffer ; } } return false ; } string GetFileVersion ( HMODULE hModule ) { string str ; WORD buffer [ 4 ]; if ( GetFileVersion ( hModule , buffer )) { char str2 [ 32 ]; for ( int i = 0 ; i < sizeof ( buffer )/ sizeof ( WORD ); i ++) { itoa ( buffer [ i ], str2 , 10 ); str += str2 ; if ( i != sizeof ( buffer )/ sizeof ( WORD ) - 1 ) { str += "." ; } } } return str ; } void main () { cout << "Current version is: " << GetFileVersion (:: GetModuleHandle ( NULL )) << endl ; } |
2.获得其他exe或dll的版本信息
std::string GetFileVersion(const std::string &strFilePath)
{
DWORD dwSize;
DWORD dwRtn;
std::string szVersion;
//获取版本信息大小
dwSize = GetFileVersionInfoSize(_T(strFilePath.c_str()),NULL);
if (dwSize == 0)
{
return "";
}
char *pBuf;
pBuf= new char[dwSize + 1];
if(pBuf == NULL)
return "";
memset(pBuf, 0, dwSize + 1);
//获取版本信息
dwRtn = GetFileVersionInfo(_T(strFilePath.c_str()),NULL, dwSize, pBuf);
if(dwRtn == 0)
{
return "";
}
LPVOID lpBuffer = NULL;
UINT uLen = 0;
//版本资源中获取信息
dwRtn = VerQueryValue(pBuf,
TEXT("\\StringFileInfo\\080404b0\\FileVersion"), //0804中文
//04b0即1252,ANSI
//可以从ResourceView中的Version中BlockHeader中看到
//可以测试的属性
/*
CompanyName
FileDescription
FileVersion
InternalName
LegalCopyright
OriginalFilename
ProductName
ProductVersion
Comments
LegalTrademarks
PrivateBuild
SpecialBuild
*/
&lpBuffer,
&uLen);
if(dwRtn == 0)
{
return "";
}
szVersion = (char*)lpBuffer;
delete pBuf;
return szVersion;
}
void main()
{
std::string strFilePath = "abc.exe";
cout << strFilePath << " version is: " << GetFileVersion(strFilePath) << endl;
}