Search code examples
c#visual-studio-2012usbdetect

C# detect last connected usb drives USB Protocol (usb3 or 2)


I'm trying to write a simple lightweight app that will tell you if the last connected usb drive was negotiated at usb 3 or usb 2 speeds. So far I have only succeeded to show the last connected drive with Win32_DiskDrive, with some open source code, but I cannot retrieve any information about the device speed that it is running. I found that Win32_USBControllerDevice does have a "negotiatedspeed" property. But I can't find any helpful resources on how to build a console app with that. perhaps someone has a code snippet for me to use? thank you for your help!


Solution

  • I've got a working solution I found here.

    USB devices

    How it works? Well, it enumerates the USB Host Controllers. gets the Root Hub and enumerates the ports that owns it. If there is a device connected and it's not a hub then it displays the required information as followings:

    Example code:

        private static void Main( string[] args )
        {
            var hostCtrls = USB.GetHostControllers();
    
            foreach ( var hostCtrl in hostCtrls )
            {
                var hub = hostCtrl.GetRootHub();
                foreach ( var port in hub.GetPorts() )
                {
                    if ( port.IsDeviceConnected && !port.IsHub )
                    {
                        var device = port.GetDevice();
                        Console.WriteLine( "Serial: " + device.DeviceSerialNumber );
                        Console.WriteLine( "Name: " + device.Name );
                        Console.WriteLine( "Speed:  " + port.Speed );
                        Console.WriteLine( "Port:   " + device.PortNumber + Environment.NewLine );
                    }
                }
            }
            Console.ReadLine();
        }