我正在尝试提取可执行文件的文件描述。右键单击文件,选择“属性”,然后在“常规”选项卡中,便会看到文件描述。
我尝试使用在https://docs.microsoft.com/en-us/windows/desktop/api/winver/nf-winver-verqueryvaluea中找到的算法,但是对于某些文件,返回的文件描述为空,尽管我可以在“属性”窗口中看到它。例如,如果我创建一个可执行文件,则返回的文件描述将为空,但是在“属性”窗口中,其文件描述与其名称相同。如何为“常规”选项卡中包含一个可执行文件且没有空字符串的每个可执行文件提取文件描述?
我按以下顺序使用这些功能:
GetFileVersionInfoSize
GetFileVersionInfo
VerQueryValue
StringCchPrintfW
VerQueryValue
StringCchCopyNW
有时它在VerQueryValue失败,有时在GetFileVersionInfo失败。我还注意到Microsoft.Photos.exe
失败答案 0 :(得分:2)
如果您想模仿shell的行为,请使用shell API,特别是property system。
可以使用一组预定义的常量来查询属性对话框中显示的大多数数据,这些预定义的常量在“ Propkey.h”中定义。在这种情况下,我们需要System.FileDescription property。要查询它,我们需要它的PKEY,DateTimeIndex
。
查询属性的最简单方法之一是IShellItem2::GetString()
方法。 out参数PKEY_FileDescription
返回一个指向字符串的指针,必须使用ppsz
将其释放。该参考文献未提及,但这是释放外壳程序为您分配的内存的常用方法。
要从文件系统路径获取IShellItem2接口,我们可以使用SHCreateItemFromParsingName()
。
在以下示例中,我将可重用代码包装在函数CoTaskMemFree()
中。
示例C ++控制台应用程序:
GetShellPropStringFromPath()
输出:
#include <Windows.h>
#include <ShlObj.h> // Shell API
#include <Propkey.h> // PKEY_* constants
#include <atlbase.h> // CComPtr, CComHeapPtr
#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <string>
#include <system_error>
// Wrapper for SHCreateItemFromParsingName(), IShellItem2::GetString()
// Throws std::system_error in case of any error.
std::wstring GetShellPropStringFromPath( LPCWSTR pPath, PROPERTYKEY const& key )
{
// Use CComPtr to automatically release the IShellItem2 interface when the function returns
// or an exception is thrown.
CComPtr<IShellItem2> pItem;
HRESULT hr = SHCreateItemFromParsingName( pPath, nullptr, IID_PPV_ARGS( &pItem ) );
if( FAILED( hr ) )
throw std::system_error( hr, std::system_category(), "SHCreateItemFromParsingName() failed" );
// Use CComHeapPtr to automatically release the string allocated by the shell when the function returns
// or an exception is thrown (calls CoTaskMemFree).
CComHeapPtr<WCHAR> pValue;
hr = pItem->GetString( key, &pValue );
if( FAILED( hr ) )
throw std::system_error( hr, std::system_category(), "IShellItem2::GetString() failed" );
// Copy to wstring for convenience
return std::wstring( pValue );
}
int main()
{
CoInitialize( nullptr ); // TODO: error handling
_setmode( _fileno( stdout ), _O_U16TEXT ); // for proper UTF-16 console output
try
{
// Show some properties of Microsoft.Photos.exe (adjust path if necessary)
LPCWSTR path = LR"(C:\Program Files\WindowsApps\Microsoft.Windows.Photos_2018.18061.17410.0_x64__8wekyb3d8bbwe\Microsoft.Photos.exe)";
std::wcout << L"PKEY_FileDescription: "
<< GetShellPropStringFromPath( path, PKEY_FileDescription ) << std::endl;
std::wcout << L"PKEY_Software_ProductName: "
<< GetShellPropStringFromPath( path, PKEY_Software_ProductName ) << std::endl;
}
catch( std::system_error const& e )
{
std::wcout << L"ERROR: " << e.what() << L"\nError code: " << e.code() << std::endl;
}
CoUninitialize();
}