获取当前程序的版本和获取某个文件的版本

时间:2021-07-21 13:59:11

                     软件更新需要获取当前程序的版本和获取某个文件的版本,在网上找了两段代码记录下来

                    1.获取某个文件的版本

                     

BOOL GetFileVersion(LPCTSTR strFile, CString& strVersion)
{
	TCHAR szVersionBuffer[8192] = _T("");
	DWORD dwVerSize;
	DWORD dwHandle;
	dwVerSize = GetFileVersionInfoSize(strFile, &dwHandle);
	if (dwVerSize == 0)
	{
		return FALSE;
	}
	if (GetFileVersionInfo(strFile, 0, dwVerSize, szVersionBuffer))
	{
		VS_FIXEDFILEINFO *pInfo;
		unsigned int nInfolen;
		if (VerQueryValue(szVersionBuffer, _T("\\"), (void**)&pInfo, &nInfolen))
		{
			strVersion.Format(_T("%d.%d.%d.%d"),
				HIWORD(pInfo->dwFileVersionMS),
				LOWORD(pInfo->dwFileVersionMS),
				HIWORD(pInfo->dwFileVersionLS),
				LOWORD(pInfo->dwFileVersionLS));
			return TRUE;
		}
	}
	return FALSE;
}

2.获取当前程序的版本

CString GetVersion()
{
	CString strVersion;
	TCHAR szFullPath[MAX_PATH];

	DWORD dwVerInfoSize = 0;
	DWORD dwVerHnd;
	VS_FIXEDFILEINFO * pFileInfo;

	GetModuleFileName(NULL, szFullPath, sizeof(szFullPath));
	dwVerInfoSize = GetFileVersionInfoSize(szFullPath, &dwVerHnd);
	if (dwVerInfoSize)
	{
		
		HANDLE hMem;
		LPVOID lpvMem;
		unsigned int uInfoSize = 0;

		hMem = GlobalAlloc(GMEM_MOVEABLE, dwVerInfoSize);
		lpvMem = GlobalLock(hMem);
		GetFileVersionInfo(szFullPath, dwVerHnd, dwVerInfoSize, lpvMem);

		::VerQueryValue(lpvMem, (LPTSTR)_T("\\"), (void**)&pFileInfo, &uInfoSize);

		int ret = GetLastError();
		WORD m_nProdVersion[4];

	
		m_nProdVersion[0] = HIWORD(pFileInfo->dwProductVersionMS);
		m_nProdVersion[1] = LOWORD(pFileInfo->dwProductVersionMS);
		m_nProdVersion[2] = HIWORD(pFileInfo->dwProductVersionLS);
		m_nProdVersion[3] = LOWORD(pFileInfo->dwProductVersionLS);


		strVersion.Format(_T("%d.%d.%d.%d"), m_nProdVersion[0],
			m_nProdVersion[1], m_nProdVersion[2], m_nProdVersion[3]);

		GlobalUnlock(hMem);
		GlobalFree(hMem);


	}
	return strVersion;
}