Following example shows reading and writing tags to the properties of a .jpg image -
#include <ShlObj.h>
#include <propvarutil.h>
#include <propkey.h>
#pragma comment(lib, "propsys")
#include <stdio.h>
#include <tchar.h>
HRESULT ReadTags(PCWSTR szImage)
{
HRESULT hr;
IPropertyStore* pStore{};
hr = SHGetPropertyStoreFromParsingName(szImage, nullptr, GPS_DEFAULT, IID_PPV_ARGS(&pStore));
if (SUCCEEDED(hr) && pStore)
{
PROPVARIANT propTags;
PropVariantInit(&propTags);
hr = pStore->GetValue(PKEY_Keywords, &propTags);
if (SUCCEEDED(hr))
{
switch (propTags.vt)
{
case VT_EMPTY:
wprintf_s(L"Image %s has no tags\n", szImage);
break;
case VT_VECTOR | VT_LPWSTR:
{
PWSTR pwszTags[10]{};
ULONG cElem{ 0 };
hr = PropVariantToStringVector(propTags, pwszTags, ARRAYSIZE(pwszTags), &cElem);
if (SUCCEEDED(hr))
{
wprintf_s(L"Image %s contained %d tags\n", szImage, cElem);
for (ULONG i = 0; i < cElem; i++)
{
wprintf_s(L"Tag %d is %s\n", i, pwszTags[i]);
CoTaskMemFree(pwszTags[i]);
}
}
else
wprintf_s(L"PropVariantToStringVector failed error was 0x%X\n", hr);
PropVariantClear(&propTags);
}
break;
default:
wprintf(L"Unexpected type %d in propvariant\n", propTags.vt);
}
}
pStore->Release();
}
return hr;
}
HRESULT WriteTags(PCWSTR szImage)
{
HRESULT hr;
IPropertyStore* pStore{};
hr = SHGetPropertyStoreFromParsingName(szImage, nullptr, GPS_READWRITE, IID_PPV_ARGS(&pStore));
if (SUCCEEDED(hr) && pStore)
{
PROPVARIANT propTags;
PCWSTR aTags[] =
{
L"First",
L"Second",
L"Third"
};
PropVariantInit(&propTags);
hr = InitPropVariantFromStringVector(aTags, ARRAYSIZE(aTags), &propTags);
if (SUCCEEDED(hr))
{
hr = pStore->SetValue(PKEY_Keywords, propTags);
if (SUCCEEDED(hr))
{
hr = pStore->Commit();
if (SUCCEEDED(hr))
wprintf_s(L"Property Tags Written to %s\n", szImage);
else
wprintf_s(L"IPropertyStore::Commit failed error was 0x%X\n", hr);
}
else
wprintf_s(L"IPropertyStore::SetValue failed error was 0x%X\n", hr);
}
PropVariantClear(&propTags);
pStore->Release();
}
return hr;
}
int main()
{
if (SUCCEEDED(CoInitialize(NULL)))
{
PCWSTR pwszImage = L"C:\\Users\\Rlwa32\\Pictures\\IMG_1874.jpg";
ReadTags(pwszImage);
WriteTags(pwszImage);
ReadTags(pwszImage);
}
CoUninitialize();
return 0;
}
Properties before -
Program output -
Properties after -