[英]How to find usb devices in c#?
我需要遍歷連接到計算機的端口,並找到特定的設備。 請看下面的圖片:
您可以看到有4個設備名稱具有相同的供應商和產品ID。 但是,我需要找到第一個的端口,它以藍色突出顯示。 看起來他們唯一的區別就是朋友的名字(描述是朋友的名字)。
在C#.net中實現這一目標的最簡單方法是什么? 我在'qt'中完成了這個,我需要知道如何使用vs 2010 professional在C#,。net framework 4中完成此操作。 我已經經歷了這樣的問題了這樣 ,但你可以看到,他們是我的情況沒有幫助。
如果你使用libusbdotnet,你應該可以做這樣的事情:
public static void RetrieveUSBDevices(int vid, int pid)
{
var usbFinder = new UsbDeviceFinder(vid, pid);
var usbDevices = new UsbRegDeviceList();
usbDevices = usbDevices.FindAll(usbFinder);
}
然后,您應該能夠迭代usbDevices並檢查正確的FullName 。 雖然這是理論上的,但我沒有對此進行測試。
更新 :試過,它工作正常 - 問題是什么? 為什么因為你自己的無能而退縮?
這也有效:
private static void Method()
{
var list = GetMyUSBDevices();
//Iterate list here and use Description to find exact device
}
private static List<UsbDevice> GetMyUSBDevices()
{
var vid = 32903;
var pid = 36;
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
collection = searcher.Get();
var usbDevice =
(from ManagementBaseObject device in collection
select new UsbDevice(
(string) device.GetPropertyValue("DeviceID"),
(string) device.GetPropertyValue("Description"))).ToList();
var devices = new List<UsbDevice>();
foreach (var device in collection)
{
devices.Add(new UsbDevice(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return (from d in devices where d.DeviceId.Contains("VID_") && d.DeviceId.Contains("PID_") && d.PID.Equals(pid) && d.VID.Equals(vid) select d).ToList();
}
public class UsbDevice
{
public UsbDevice(string deviceId, string description)
{
DeviceId = deviceId;
Description = description;
}
public string DeviceId { get; private set; }
public string Description { get; private set; }
public int VID
{
get { return int.Parse(GetIdentifierPart("VID_"), System.Globalization.NumberStyles.HexNumber); }
}
public int PID
{
get { return int.Parse(GetIdentifierPart("PID_"), System.Globalization.NumberStyles.HexNumber); }
}
private string GetIdentifierPart(string identifier)
{
var vidIndex = DeviceId.IndexOf(identifier, StringComparison.Ordinal);
var startingAtVid = DeviceId.Substring(vidIndex + 4);
return startingAtVid.Substring(0, 4);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.