VC++ 获取exe或者dll版本信息

时间:2021-02-08 14:02:26
#include <iostream>
#include <atlstr.h>
#pragma comment(lib,"version.lib")

CString GetFileVersion(CString strExePath)
{
    DWORD   dwVerInfoSize = 0;
    DWORD dwVerHnd = 0;
    char   *pBuf;
    CString   asVer;
    VS_FIXEDFILEINFO   *pVsInfo;
    unsigned   int   iFileInfoSize = sizeof(VS_FIXEDFILEINFO);
    dwVerInfoSize = GetFileVersionInfoSize(strExePath, NULL);//将版本信息资源读入缓冲区

    if (dwVerInfoSize)
    {
        pBuf = new char[dwVerInfoSize];
        if (GetFileVersionInfo(strExePath, dwVerHnd, dwVerInfoSize, pBuf))//获得生成文件使用的代码页及文件版本
        {
            struct LANGANDCODEPAGE
            {
                WORD    wLanguage;
                WORD    wCodePage;
            }*lpTranslate;

            if (VerQueryValue(pBuf, _T("\\VarFileInfo\\Translation"), (void**)&lpTranslate, &iFileInfoSize))
            {
                unsigned int version_len = 0;
                if (VerQueryValue(pBuf, _T("\\"), (void**)&pVsInfo, &version_len))
                {
                    asVer.Format(_T("%d.%d.%d.%d"), HIWORD(pVsInfo->dwFileVersionMS),
                        LOWORD(pVsInfo->dwFileVersionMS),
                        HIWORD(pVsInfo->dwFileVersionLS),
                        LOWORD(pVsInfo->dwFileVersionLS));
                }
            }
        }
        delete   pBuf;
    }
    return   asVer;
}

int main()
{
    //获取工作路径
    TCHAR    szModulePath[MAX_PATH * 2];
    ::GetModuleFileName(NULL, szModulePath, _countof(szModulePath) - 2);
    PathRemoveFileSpec(szModulePath);
    CString strExe = szModulePath;

    strExe += L"\\My.dll";

    CString strver = GetFileVersion(strExe);

    return 0;
}