List connected USB devices in Windows using C#
Question:
How to identify and get information about all USB devices connected to Windows system?
Solution:
By integrating the System.Management
namespace into your project, you can retrieve the list of USB devices using the following code:
<code class="language-csharp">using System; using System.Collections.Generic; using System.Management; // 将 System.Management 添加到您的项目引用中。 public class Program { public static void Main(string[] args) { var usbDevices = GetUSBDevices(); foreach (var usbDevice in usbDevices) { Console.WriteLine( $"设备 ID:{usbDevice.DeviceID},PNP 设备 ID:{usbDevice.PnpDeviceID},描述:{usbDevice.Description}"); } Console.ReadKey(); } public static List<USBDeviceInfo> GetUSBDevices() { var devices = new List<USBDeviceInfo>(); using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub")) using (var collection = searcher.Get()) { foreach (var device in collection) { devices.Add(new USBDeviceInfo( (string)device.GetPropertyValue("DeviceID"), (string)device.GetPropertyValue("PNPDeviceID"), (string)device.GetPropertyValue("Description") )); } } return devices; } } public class USBDeviceInfo { public USBDeviceInfo(string deviceID, string pnpDeviceID, string description) { DeviceID = deviceID; PnpDeviceID = pnpDeviceID; Description = description; } public string DeviceID { get; private set; } public string PnpDeviceID { get; private set; } public string Description { get; private set; } }</code>
This solution uses the System.Management
namespace to access the ManagementObjectSearcher
class, allowing you to query the Win32_USBHub
class to find USB devices. The code iterates over the returned collection to extract relevant information such as device ID, PNP device ID, and description, providing a complete list of connected USB devices.
The above is the detailed content of How Can I List All Connected USB Devices in Windows Using C#?. For more information, please follow other related articles on the PHP Chinese website!