我想要 C#.NET 中连接的 USB 设备的列表。但我不明白该怎么做。
问问题
10056 次
1 回答
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; }
}
}
希望它可以帮助你。
于 2013-05-06T11:00:23.047 回答