Creating WPD PROPVARIANTs in C# without using interop
Previous posts have covered how to create, manage and marshal PROPVARIANTs using interop. Here's a way on how to create a PROPVARIANT without interop.
The IPortableDeviceValues interface exposes a SetStringValue method that allows a regular C# string to be added into the collection. IPortableDeviceValues also exposes a GetValue method which lets us retrieve any added property value as a PROPVARIANT. Armed with these two facts, it's pretty obvious how we can manufacture a string PROPVARIANT.
static void StringToPropVariant(string value,
out PortableDeviceApiLib.tag_inner_PROPVARIANT propvarValue)
{
// We'll use an IPortableDeviceValues object to transform the
// string into a PROPVARIANT
PortableDeviceApiLib.IPortableDeviceValues pValues =
(PortableDeviceApiLib.IPortableDeviceValues)
new PortableDeviceTypesLib.PortableDeviceValuesClass();
// We insert the string value into the IPortableDeviceValues object
// using the SetStringValue method
pValues.SetStringValue(ref PortableDevicePKeys.WPD_OBJECT_ID, value);
// We then extract the string into a PROPVARIANT by using the
// GetValue method
pValues.GetValue(ref PortableDevicePKeys.WPD_OBJECT_ID,
out propvarValue);
}
We create an instance of an IPortableDeviceValues object named pValues. We then call SetStringValue with a dummy property key and the string to be converted. pValues now contains exactly one item - a string value which is internally held as a PROPVARIANT. To extract the internally held PROPVARIANT, we call GetValue which returns us a PROPVARIANT value.
This example function can be extended for other PROPVARIANT types. Use Object Browser and take a look at the Set* methods exposed by IPortableDeviceValues. Follow the same paradigm - use Set*Value for your source target type and then use GetValue to extract it as a PROPVARIANT.