在 C# 中从 Win32_PnPEntity 获取 DEVPKEY_Device_BusReportedDeviceDesc

Get DEVPKEY_Device_BusReportedDeviceDesc from Win32_PnPEntity in c#

我正在尝试从我们的 WPF 应用程序中的 usb com 端口获取总线报告的设备描述。找到了一个 powershell 脚本,它给出了 exacly,但由于不是每个用户都有权使用 运行 powershell,所以使用 PowerShell.Create() 很遗憾不是一个选项。

(Get-WMIObject Win32_PnPEntity | where {$_.name -match "\(com*"}).GetDeviceProperties("DEVPKEY_Device_BusReportedDeviceDesc").DeviceProperties.Data

我尝试了以下组合,但我在 InvokeMethod 上得到“无法将类型 'System.String' 的对象转换为类型 'System.Array'”或“无效的方法参数”。

using System;
using System.Management;

ManagementClass oClass = new ManagementClass("Win32_PnPEntity");

Object[] single = { "DEVPKEY_Device_BusReportedDeviceDesc" };
Array arr = (Array)new string[] { "DEVPKEY_Device_BusReportedDeviceDesc" };
Object[] singleArr = { single };
Object[] objsArr = { arr };
ManagementBaseObject inParams = oClass.GetMethodParameters("GetDeviceProperties");
inParams["devicePropertyKeys"] = single;
//inParams["devicePropertyKeys"] = arr;
//inParams["devicePropertyKeys"] = singleArr;
//inParams["devicePropertyKeys"] = objsArr;

oClass.InvokeMethod("GetDeviceProperties", single);
//oClass.InvokeMethod("GetDeviceProperties", singleArr);
//oClass.InvokeMethod("GetDeviceProperties", objsArr);
//oClass.InvokeMethod("GetDeviceProperties", inParams, null);

一切都在本地机器上进行。

还从 vromanov How to get Bus Reported Device Description using C# 找到了答案,它有效,但似乎是一个矫枉过正的解决方案

GetDeviceProperties 方法记录如下:

Uint32 GetDeviceProperties(
  [in, optional] string                  devicePropertyKeys[],
  [out]          Win32_PnPDeviceProperty deviceProperties[]
);

所以这是一个用 C# 调用它的示例代码:

foreach (var mo in new ManagementObjectSearcher(null, "SELECT * FROM Win32_PnPEntity").Get().OfType<ManagementObject>())
{
    // get the name so we can do some tests on the name in this case
    var name = mo["Name"] as string;

    // add your custom test here
    if (name == null || name.IndexOf("(co", StringComparison.OrdinalIgnoreCase) < 0)
        continue;

    // call Win32_PnPEntity's 'GetDeviceProperties' method
    // prepare two arguments:
    //  1st one is an array of string (or null)
    //  2nd one will be filled on return (it's an array of ManagementBaseObject)
    var args = new object[] { new string[] { "DEVPKEY_Device_BusReportedDeviceDesc" }, null };
    mo.InvokeMethod("GetDeviceProperties", args);

    // one mbo for each device property key
    var mbos = (ManagementBaseObject[])args[1];
    if (mbos.Length > 0)
    {
        // get value of property named "Data"
        // not all objects have that so we enum all props here
        var data = mbos[0].Properties.OfType<PropertyData>().FirstOrDefault(p => p.Name == "Data");
        if (data != null)
        {
            Console.WriteLine(data.Value);
        }
    }
}