gpt4 book ai didi

c# - 获取连接的 USB 设备列表

转载 作者:可可西里 更新时间:2023-11-01 03:11:29 24 4
gpt4 key购买 nike

如何获取 Windows 计算机上所有连接的 USB 设备的列表?

最佳答案

为您的项目添加对 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}, 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_USBHub"))
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; }
}
}

关于c# - 获取连接的 USB 设备列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18073916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com