使用C++提供的一个查询文件信息的接口,实现接口为 QueryValue
。
fileInfo.h
class FileInfoUtils
{
public:
static bool GetFileDescription(const std::wstring& szModuleName, std::wstring& RetStr) {return QueryValue(L"FileDescription",szModuleName,RetStr);}
static bool GetFileVersion(const std::wstring& szModuleName, std::wstring& RetStr) {return QueryValue(L"FileVersion",szModuleName,RetStr);}
static bool GetInternalName(const std::wstring& szModuleName, std::wstring& RetStr) {return QueryValue(L"InternalName",szModuleName,RetStr);}
static bool GetCompanyName(const std::wstring& szModuleName, std::wstring& RetStr) {return QueryValue(L"CompanyName",szModuleName,RetStr);}
static bool GetLegalCopyright(const std::wstring& szModuleName, std::wstring& RetStr) {return QueryValue(L"LegalCopyright",szModuleName,RetStr);}
static bool GetOriginalFilename(const std::wstring& szModuleName, std::wstring& RetStr) {return QueryValue(L"OriginalFilename",szModuleName,RetStr);}
static bool GetProductName(const std::wstring& szModuleName, std::wstring& RetStr) {return QueryValue(L"ProductName",szModuleName,RetStr);}
static bool GetProductVersion(const std::wstring& szModuleName, std::wstring& RetStr) {return QueryValue(L"ProductVersion",szModuleName,RetStr);}
private:
static bool QueryValue(const std::wstring wsValueName, const std::wstring wsModuleName, std::wstring &wsRetStr);
};
fileInfo.cpp
bool FileInfoUtils::QueryValue(const std::wstring wsValueName, const std::wstring wsModuleName, std::wstring &wsRetStr)
{
bool bSuccess = FALSE;
BYTE *lpVersionData = NULL;
DWORD dwLangCharset = 0;
TCHAR *pStr = NULL;
do
{
if ( wsValueName.empty() || wsModuleName.empty() )
break;
DWORD dwHandle;
// 判断系统能否检索到指定文件的版本信息
DWORD dwDataSize = ::GetFileVersionInfoSize((LPCWSTR)wsModuleName.c_str(), &dwHandle);
if (dwDataSize == 0)
break;
lpVersionData = new (std::nothrow) BYTE[dwDataSize];// 分配缓冲区
if ( NULL == lpVersionData)
break;
// 检索信息
if (!::GetFileVersionInfo((LPCWSTR)wsModuleName.c_str(), dwHandle, dwDataSize, (void*)lpVersionData))
break;
UINT nQuerySize;
DWORD *pTransTable;
// 设置语言
if ( !::VerQueryValue(lpVersionData, L"\\VarFileInfo\\Translation", (void **)&pTransTable, &nQuerySize))
break;
dwLangCharset = MAKELONG(HIWORD(pTransTable[0]), LOWORD(pTransTable[0]));
if (lpVersionData == NULL)
break;
pStr = new (std::nothrow) TCHAR[128];// 分配缓冲区
if (NULL == pStr)
break;
//wchar_t str2[MAX_PATH];
//wcscpy_s(str2, MAX_PATH, wsValueName.c_str());
swprintf_s(pStr, 128, L"\\StringFileInfo\\%08lx\\%s", dwLangCharset, wsValueName.c_str());
LPVOID lpData;
// 调用此函数查询前需要先依次调用函数GetFileVersionInfoSize和GetFileVersionInfo
if (::VerQueryValue((void *)lpVersionData, pStr, &lpData, &nQuerySize))
wsRetStr = (TCHAR *)lpData;
bSuccess = TRUE;
} while (FALSE);
// 销毁缓冲区
if (lpVersionData)
{
delete[] lpVersionData;
lpVersionData = NULL;
}
if (pStr)
{
delete[] pStr;
pStr = NULL;
}
return bSuccess;
}