I am attempting to enumerate connected portable devices on Windows using the Windows Portable Devices API and the PortableDeviceManager provided by this API.
I have implemented enumeration of device IDs following the MSDN documentation link and various blogs link, but they all result in the same issue - I can only get it to give me the ID of one device when there are several connected.
Here's the snippet of C# code I am using:
PortableDeviceManagerClass deviceManager = new PortableDeviceManagerClass();
uint numberOfDevices = 1;
deviceManager.GetDevices(null, ref numberOfDevices);
if (numberOfDevices == 0)
return new string;
string  deviceIds = new string[numberOfDevices];
deviceManager.GetDevices(ref deviceIds, ref numberOfDevices);
Take a look at the following post by the WPD team, it mentions how you can fix the interop assembly.
Just to be complete, I'll mention the answer here as well:
This is due to a marshalling restriction. This sample code will only detect one device. You need to manually fix the interop assembly.
Disassemble the PortableDeviceApi Interop assembly using the command:
ildasm Interop.PortableDeviceApiLib.dll /out:pdapi.il
Open the IL in Notepad and search for the following string:
instance void GetDevices([in][out] string& marshal( lpwstr) pPnPDeviceIDs,
Replace all instances of the string above with the following string:
instance void GetDevices([in][out] string marshal() pPnPDeviceIDs,
Save the IL and reassemble the interop using the command:
ilasm pdapi.il /dll /output=Interop.PortableDeviceApiLib.dll
Rebuild your project. You can now first call
GetDevices with a
NULL parameter to get the count of devices and then call it again with an array to get the device IDs.
Hope this helps.