时间:2010-07-25 21:17:18

标签: c# usb

8 个答案:

答案 0 :(得分:103)

答案 1 :(得分:32)

我知道我回答了一个老问题,但我刚刚完成了同样的练习并找到了更多信息,我认为这些信息会为讨论做出很多贡献并帮助其他发现这一点的人问题并看到现有答案不足的地方。

accepted answer已关闭,可以使用Nedko's comment进行更正。对WMI类的更详细了解有助于完成图片。

Win32_USBHub仅返回USB 集线器。事后看来这很明显,但上面的讨论错过了它。它不包括所有可能的USB设备,只有那些能够(理论上至少)充当其他设备的集线器的设备。它错过了一些不是集线器的设备(特别是复合设备的部件)。

Win32_PnPEntity包括所有USB设备和数百个非USB设备。 Russel Gantman's建议使用WHERE子句搜索Win32_PnPEntity来获取以&#34开头的DeviceID; USB%"筛选列表是有帮助的,但稍微不完整;它错过了蓝牙设备,一些打印机/打印服务器以及符合HID标准的鼠标和键盘。我见过" USB \%"," USBSTOR \%"," USBPRINT \%"," BTH \%" ," SWD \%"和" HID \%"。然而,Win32_PnPEntity是一位优秀的"大师"一旦您拥有来自其他来源的PNPDeviceID,就可以参考查找信息。

我发现枚举USB设备的最佳方法是查询Win32_USBControllerDevice。虽然它没有提供设备的详细信息,但它确实完全枚举了您的USB设备,并为每个USB设备(包括集线器,非集线器设备和设备)提供了PNPDeviceID的前提/从属对。系统上的HID兼容设备)。从查询返回的每个Dependent将是USB设备。 Antecedent将是它所分配的控制器,其中一个是通过查询Win32_USBController返回的USB控制器。

作为奖励,看起来在引擎盖下,WMI在响应Win32_USBControllerDevice查询时走Device Tree,因此返回这些结果的顺序可以帮助识别父/子关系。 (这没有记录,因此只是猜测;使用SetupDi API CM_Get_Parent(或Child + Sibling)获得明确的结果。)作为SetupDi的选项API,似乎对于Win32_USBHub下列出的所有设备,可以在注册表中查找(HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\ + PNPDeviceID),并且参数ParentIdPrefix将是最后一个的前缀其子项的PNPDeviceID中的字段,因此也可以在通配符匹配中使用它来过滤Win32_PnPEntity查询。

在我的申请中,我做了以下事情:

  • (可选)查询Win32_PnPEntity并将结果存储在键值映射中(以PNPDeviceID作为键)以便以后检索。如果您想稍后进行单独查询,这是可选的。
  • 查询Win32_USBControllerDevice我系统上的USB设备(所有家属)的确切列表,并提取这些的PNPDeviceID。我根据设备树之后的顺序进一步将设备分配给根集线器(返回的第一个设备,而不是控制器),并基于parentIdPrefix构建了一个树。查询返回的顺序(通过SetupDi匹配设备树枚举)是每个根集线器(Antecedent为其识别控制器),然后是其下的设备迭代,例如,在我的系统上:
    • 第一个控制器的根集线器
    • 第二个控制器的根集线器
      • 第二个控制器的根集线器下的第一个集线器(具有parentIdPrefix)
        • 第一个集线器位于第二个控制器的根集线器下的第一个集线器下(PNPDeviceID匹配以上集线器的ParentIdPrefix;具有自己的ParentIdPrefix)
          • 复合设备的HID设备部分(PNPDeviceID匹配以上复合设备' ParentIDPrefix)
        • 第二个设备位于第二个控制器根集线器下的第一个集线器下
          • 复合设备的HID设备部分
      • 第二个控制器根集线器下的第二个集线器
        • 第二个集线器位于第二个控制器根集线器下的第二个设备
      • 第二个控制器的根集线器下的第三个集线器
  • 查询Win32_USBController。这给了我控制器的PNPDeviceID的详细信息,这些控制器位于设备树的顶部(这是前一个查询的前提)。使用上一步中派生的树,递归迭代其子节点(根集线器)及其子节点(其他集线器)及其子节点(非集线器设备和复合设备)及其子节点等。
    • 通过引用第一步中存储的地图检索树中每个设备的详细信息。 (可选地,可以跳过第一步,并使用PNPDeviceId单独查询Win32_PnPEntity以获取此步骤的信息;可能是cpu与内存权衡确定哪个顺序更好。)

总之,Win32USBControllerDevice依赖项是系统上USB设备的完整列表(控制器本身除外,它们是同一查询中的前提),并通过交叉引用这些PNPDeviceId与来自注册表和所提到的其他查询的信息配对,可以构建详细的图片。

答案 2 :(得分:12)

要查看我感兴趣的设备,我已根据this post在Adel Hazzah的代码中将Win32_USBHub替换为Win32_PnPEntity。这对我有用:

namespace ConsoleApplication1
{
  using System;
  using System.Collections.Generic;
  using System.Management; // need to add System.Management to your project references.

  class Program
  {
    static void Main(string[] args)
    {
      var usbDevices = GetUSBDevices();

      foreach (var usbDevice in usbDevices)
      {
        Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
            usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
      }

      Console.Read();
    }

    static List<USBDeviceInfo> GetUSBDevices()
    {
      List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

      ManagementObjectCollection collection;
      using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
        collection = searcher.Get();      

      foreach (var device in collection)
      {
        devices.Add(new USBDeviceInfo(
        (string)device.GetPropertyValue("DeviceID"),
        (string)device.GetPropertyValue("PNPDeviceID"),
        (string)device.GetPropertyValue("Description")
        ));
      }

      collection.Dispose();
      return devices;
    }
  }

  class USBDeviceInfo
  {
    public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
    {
      this.DeviceID = deviceID;
      this.PnpDeviceID = pnpDeviceID;
      this.Description = description;
    }
    public string DeviceID { get; private set; }
    public string PnpDeviceID { get; private set; }
    public string Description { get; private set; }
  }
}

答案 3 :(得分:4)

对于仅寻找可移动USB驱动器的人来说,这是一个更简单的示例。

using System.IO;

foreach (DriveInfo drive in DriveInfo.GetDrives())
{
    if (drive.DriveType == DriveType.Removable)
    {
        Console.WriteLine(string.Format("({0}) {1}", drive.Name.Replace("\\",""), drive.VolumeLabel));
    }
}

答案 4 :(得分:4)

Adel Hazzah的answer提供了工作代码,Daniel Widdis'sNedko's评论提到您需要查询Win32_USBControllerDevice并使用其Dependent属性,而Daniel&#39; s { {3}}在没有代码的情况下提供了很多细节。

以上是对上述讨论的综合,以提供列出所有已连接USB设备的可直接访问的PNP设备属性的工作代码:

using System;
using System.Collections.Generic;
using System.Management; // reference required

namespace cSharpUtilities
{
    class UsbBrowser
    {

        public static void PrintUsbDevices()
        {
            IList<ManagementBaseObject> usbDevices = GetUsbDevices();

            foreach (ManagementBaseObject usbDevice in usbDevices)
            {
                Console.WriteLine("----- DEVICE -----");
                foreach (var property in usbDevice.Properties)
                {
                    Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
                }
                Console.WriteLine("------------------");
            }
        }

        public static IList<ManagementBaseObject> GetUsbDevices()
        {
            IList<string> usbDeviceAddresses = LookUpUsbDeviceAddresses();

            List<ManagementBaseObject> usbDevices = new List<ManagementBaseObject>();

            foreach (string usbDeviceAddress in usbDeviceAddresses)
            {
                // query MI for the PNP device info
                // address must be escaped to be used in the query; luckily, the form we extracted previously is already escaped
                ManagementObjectCollection curMoc = QueryMi("Select * from Win32_PnPEntity where PNPDeviceID = " + usbDeviceAddress);
                foreach (ManagementBaseObject device in curMoc)
                {
                    usbDevices.Add(device);
                }
            }

            return usbDevices;
        }

        public static IList<string> LookUpUsbDeviceAddresses()
        {
            // this query gets the addressing information for connected USB devices
            ManagementObjectCollection usbDeviceAddressInfo = QueryMi(@"Select * from Win32_USBControllerDevice");

            List<string> usbDeviceAddresses = new List<string>();

            foreach(var device in usbDeviceAddressInfo)
            {
                string curPnpAddress = (string)device.GetPropertyValue("Dependent");
                // split out the address portion of the data; note that this includes escaped backslashes and quotes
                curPnpAddress = curPnpAddress.Split(new String[] { "DeviceID=" }, 2, StringSplitOptions.None)[1];

                usbDeviceAddresses.Add(curPnpAddress);
            }

            return usbDeviceAddresses;
        }

        // run a query against Windows Management Infrastructure (MI) and return the resulting collection
        public static ManagementObjectCollection QueryMi(string query)
        {
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection result = managementObjectSearcher.Get();

            managementObjectSearcher.Dispose();
            return result;
        }

    }

}

如果需要,您需要添加异常处理。如果你想找出设备树等,请咨询Daniel的答案。

答案 5 :(得分:3)

如果将ManagementObjectSearcher更改为以下内容:

ManagementObjectSearcher searcher = 
       new ManagementObjectSearcher("root\\CIMV2", 
       @"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%"""); 

所以“GetUSBDevices()看起来像这样”

static List<USBDeviceInfo> GetUSBDevices()
{
  List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

  ManagementObjectCollection collection;
  using (var searcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%"""))
    collection = searcher.Get();      

  foreach (var device in collection)
  {
    devices.Add(new USBDeviceInfo(
    (string)device.GetPropertyValue("DeviceID"),
    (string)device.GetPropertyValue("PNPDeviceID"),
    (string)device.GetPropertyValue("Description")
    ));
  }

  collection.Dispose();
  return devices;
}

}

您的结果仅限于USB设备(与系统上的所有类型相反)

答案 6 :(得分:2)

答案 7 :(得分:0)

  lstResult.Clear();
  foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
  {
       foreach (ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
       {
            foreach (ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
            {
                  foreach (var item in disk.Properties)
                  {
                       object value = disk.GetPropertyValue(item.Name);
                  }
                  string valor = disk["Name"].ToString();
                  lstResult.Add(valor);
                  }
             }
        }
   }