獲取已連接USB設備列表
在處理USB設備時,常常需要獲取所有已連接USB設備的列表。在Windows環境中,可以使用System.Management
命名空間的ManagementObjectSearcher
類來完成此任務。
首先,為您的項目添加對System.Management
的引用。完成此操作後,您可以使用以下代碼片段來檢索已連接的USB設備列表:
<code class="language-csharp">using System; using System.Collections.Generic; using System.Management; // 需要在项目引用中添加 System.Management。 class Program { 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(); } static List<USBDeviceInfo> GetUSBDevices() { List<USBDeviceInfo> 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; } } 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>
上述代碼片段中的GetUSBDevices()
方法返回一個USBDeviceInfo
對象的列表,其中包含DeviceID
、PNPDeviceID
和Description
屬性。這些屬性分別代表設備的唯一標識符、即插即用設備ID和設備的描述。
通過使用此代碼,您可以輕鬆獲取Windows計算機上所有已連接USB設備的列表,並訪問其屬性以進行進一步處理。
以上是如何檢索Windows中連接的USB設備的列表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!