如何使用C#.NET查找USB设备列表

时间:2013-05-06 09:48:08

标签: c# usb

我想在C#.NET中列出已连接的USB设备。但我无法理解该怎么做。

1 个答案:

答案 0 :(得分:3)

在项目中添加对System.Management的引用,之后引用代码

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}", usbDevice.DeviceID);

        }

        Console.Read();
    }

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

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

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

        collection.Dispose();
        return devices;
    }
}

class USBDeviceInfo
{
    public USBDeviceInfo(string deviceID)
    {
        this.DeviceID = deviceID;
    }
    public string DeviceID { get; private set; }

}

}

希望它对你有所帮助。