#ifndef FILEVERSION_H #define FILEVERSION_H #include <string> std::string GetFileVersion(std::string strFilePath); #endif
#include "stdafx.h" #include "FileVersion.h" #include<winver.h> #pragma comment(lib,"Version.lib") std::string CorrectionStr(std::string &strValue){ size_t index = strValue.find(',',0); while(index != -1){ strValue.replace(index,1,"."); index = strValue.find(',',0); } index = strValue.find(' ',0); while(index != -1){ strValue.replace(index,1,""); index = strValue.find(' ',0); } return strValue; } std::string charToStr(UCHAR ch){ std::string str; DWORD dValue = ((ch&0xF0)>>4); str += (UCHAR)(dValue < 10 ? dValue + '0' : dValue - 10 + 'a'); dValue = (ch&0x0F); str += (UCHAR)(dValue < 10 ? dValue + '0' : dValue - 10 + 'a'); return str; } std::string Translation(PVOID buf , UINT uLen) { std::string strTra; UINT i = 0; for( ; i < uLen/(sizeof(USHORT)/sizeof(UCHAR)) ; i ++){ USHORT ush = *((USHORT*)buf + i); UCHAR ch = (ush&0xFF00)>>8; strTra += charToStr(ch); ch = ush&0xFF; strTra += charToStr(ch); } return strTra; } std::string GetVersion(std::string strFilePath , std::string strName){ if(strName.size() == 0) return (""); DWORD dwSize; DWORD dwRtn; //获取版本信息大小 dwSize = GetFileVersionInfoSizeA(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 = GetFileVersionInfoA(strFilePath.c_str(),NULL, dwSize, pBuf); if(dwRtn == 0) { delete pBuf; return ""; } LPVOID lpBuffer = NULL; UINT uLen = 0; //版本资源中获取信息 //获得语言和代码页(language and code page) dwRtn = VerQueryValueA(pBuf, (("\\VarFileInfo\\Translation")), &lpBuffer, &uLen); if(dwRtn == 0) { //部分文件的版本语言项会放到 翻译 字段中. dwRtn = VerQueryValueA(pBuf, (("\\VarFileInfo\\翻译")), &lpBuffer, &uLen); if(dwRtn == 0){ delete pBuf; return ""; } } std::string strTranslation = Translation(lpBuffer,uLen); //语言页 std::string strSubBlock = "\\StringFileInfo\\"; strSubBlock += strTranslation; strSubBlock += "\\"; strSubBlock += strName; //strSubBlock.Format("\\StringFileInfo\\%s\\FileVersion",strTranslation); lpBuffer = NULL; dwRtn = VerQueryValueA(pBuf, //_T("\\StringFileInfo\\080403a8\\FileVersion"), (LPSTR)strSubBlock.c_str(), &lpBuffer, &uLen); if(dwRtn == 0) { delete pBuf; return ""; } std::string szVersion = (char*)lpBuffer; delete pBuf; CorrectionStr(szVersion); return szVersion; } std::string GetProductVersion(std::string strFilePath) { return GetVersion(strFilePath,("ProductVersion")); } std::string GetFileVersion(std::string strFilePath) { return GetVersion(strFilePath,("FileVersion")); } // VarFileInfo\\Translation 获得语言和代码页(language and code page) //"\\StringFileInfo\\080404b0\\FileVersion", //0804中文 //04b0即1252,ANSI //可以从ResourceView中的Version中BlockHeader中看到 //可以测试的属性 /* CompanyName FileDescription FileVersion InternalName LegalCopyright OriginalFilename ProductName ProductVersion Comments LegalTrademarks PrivateBuild SpecialBuild */