我使用这个项目通过MTP获取数据:
https://github.com/notpod/wpd-lib我的问题是:设备的"友好名称"总是空的。Windows在"这台PC"下面显示了一个友好的名称,所以应该是可行的。
这就是提到的github项目如何尝试检索友好的名称(从文件WindowsPortableDevice.cs):
var WPD_DEVICE_FRIENDLY_NAME = new PortableDeviceApiLib._tagpropertykey();
WPD_DEVICE_FRIENDLY_NAME.fmtid = new Guid(0x26D4979A, 0xE643, 0x4626, 0x9E, 0x2B, 0x73, 0x6D, 0xC0, 0xC9, 0x2F, 0xDC);
WPD_DEVICE_FRIENDLY_NAME.pid = 12;
string friendlyName;
propertyValues.GetStringValue(ref DevicePropertyKeys.WPD_DEVICE_FRIENDLY_NAME, out friendlyName);
如前所述,friendlyName
的结果总是空的。
我已经试过了:
在这篇文章中,我发现了另一个可能的解决方案,它使用PortableDeviceManagerClass
而不是PortableDeviceClass
:
string RetrieveFriendlyName(
PortableDeviceApiLib.PortableDeviceManagerClass PortableDeviceManager,
string PnPDeviceID)
{
uint cFriendlyName = 0;
ushort[] usFriendlyName;
string strFriendlyName = String.Empty;
// First, pass NULL as the LPWSTR return string parameter to get the total number
// of characters to allocate for the string value.
PortableDeviceManager.GetDeviceFriendlyName(PnPDeviceID, null, ref cFriendlyName);
// Second allocate the number of characters needed and retrieve the string value.
usFriendlyName = new ushort[cFriendlyName];
if (usFriendlyName.Length > 0)
{
PortableDeviceManager.GetDeviceFriendlyName(PnPDeviceID, usFriendlyName, ref cFriendlyName);
// We need to convert the array of ushorts to a string, one
// character at a time.
foreach (ushort letter in usFriendlyName)
if (letter != 0)
strFriendlyName += (char)letter;
// Return the friendly name
return strFriendlyName;
}
else
return null;
}
这里的问题是,我似乎有一个不同的GetDeviceFriendlyName
签名(不同的Interop.PortableDeviceApiLib.dll
?)。这是我的:
void GetDeviceFriendlyName(string pszPnPDeviceID, ref ushort pDeviceFriendlyName, ref uint pcchDeviceFriendlyName);
不接受null
或ushort[]
。
我测试了下面的代码,只是为了看看它的行为:
var pDeviceFriendlyName = default(ushort);
var pcchDeviceFriendlyName = default(uint);
GetDeviceFriendlyName(pszPnPDeviceID, ref pDeviceFriendlyName, ref pcchDeviceFriendlyName);
…但是它抛出了一个异常:"The data is invalid. (Exception from HRESULT: 0x8007000D)"
.
显然Windows没有使用"友好名称"来显示"此PC"上的设备,而是使用"设备型号":
WPD_DEVICE_MODEL.fmtid = new Guid(0x26D4979A, 0xE643, 0x4626, 0x9E, 0x2B, 0x73, 0x6D, 0xC0, 0xC9, 0x2F, 0xDC);
WPD_DEVICE_MODEL.pid = 8;