How to get the VID and PID of all USB devices connected to my system in .net?

亡梦爱人 提交于 2019-12-10 11:05:02

问题


In a C#.net console application, what code can i write to print on the screen the VID and PID of each USB device connected to the system?


回答1:


Here's some code I've written based on what I've found so far. There may be a better way to do this.

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


来源:https://stackoverflow.com/questions/8303069/how-to-get-the-vid-and-pid-of-all-usb-devices-connected-to-my-system-in-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!