如何在.net中获取连接到我系统的所有USB设备的VID和PID?

时间:2011-11-28 22:09:50

标签: .net usb

在C#.net控制台应用程序中,我可以编写哪些代码在屏幕上打印连接到系统的每个USB设备的VID和PID?

1 个答案:

答案 0 :(得分:4)

这是我根据迄今为止发现的内容编写的一些代码。可能有更好的方法来做到这一点。

    public static void MyMethod()
    {                            
        System.Management.ManagementClass USBClass = new ManagementClass("Win32_USBDevice");                
        System.Management.ManagementObjectCollection USBCollection = USBClass.GetInstances();

        foreach (System.Management.ManagementObject usb in USBCollection)
        {
            string deviceId = usb["deviceid"].ToString();
            Console.WriteLine(deviceId);

            int vidIndex = deviceId.IndexOf("VID_");
            string startingAtVid = deviceId.Substring(vidIndex + 4); // + 4 to remove "VID_"                    
            string vid = startingAtVid.Substring(0, 4); // vid is four characters long
            Console.WriteLine("VID: " + vid);

            int pidIndex = deviceId.IndexOf("PID_");
            string startingAtPid = deviceId.Substring(pidIndex + 4); // + 4 to remove "PID_"                    
            string pid = startingAtPid.Substring(0, 4); // pid is four characters long
            Console.WriteLine("PID: " + pid);                                        
        }            

        Console.ReadLine();
    }