2013-05-06 67 views
0

我想要一個C#.NET中連接的USB設備列表。但我不明白該怎麼做。如何使用C#.NET找到USB設備列表

+1

你甚至試圖尋找解決方案嗎?那麼:http://stackoverflow.com/questions/3331043/get-list-of-connected-usb-devices只需在谷歌中鍵入您的問題... – bema 2013-05-06 09:53:18

+0

我需要在列表框中顯示它。我以前見過你的鏈接。但有些代碼不起作用。 錯誤\t \t 1名稱 'GetUSBDevices' 不存在於當前上下文\tģ存在:\ USB_Device_List \ USB_DEVICE \ USB_DEVICE \ Form1.cs中\t – 2013-05-06 10:08:01

+0

USB_DEVICE @MarufHossain:所述GetUSBDevices()正下方的被定義主功能。 – 2013-05-06 10:20:03

回答

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; } 

} 

}

希望它可以幫助你。