Find specific slot no of the USB Hub(10 slots) where USB is connected or not. I want to get the specific slot no where USB is connected or not

前端 未结 2 655
误落风尘
误落风尘 2021-01-23 20:53

I have a USB Hub of 10 USB slots connected to my USB Port. I want to get the USB device connected to the specific port.
Example: Two USB\'s are connected at Slot 3 and Slot

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-23 21:55

    static int GetPhysicalPort()
        {
            try
            {
                devices = new List();
                
                ManagementObjectCollection collection;
                using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPSignedDriver WHERE DeviceId LIKE 'USB\\VID%' AND Description = 'USB Mass Storage Device' "))
                {
                    collection = searcher.Get();
                    searcher.Dispose();
                }
                    
    
                foreach (var device in collection)
                {
                    devices.Add(new USBDeviceInfo(
                    (string)device.GetPropertyValue("DeviceId"),
                    (string)device.GetPropertyValue("Description"),
                    (string)device.GetPropertyValue("Location")
                    ));
                }
    
                collection.Dispose();
               
                string LastAdded = devices[0].Location.Substring(6, 4);
                Console.WriteLine(LastAdded);
                return Convert.ToInt32(LastAdded);
            }
    
            catch (Exception e)
            {
                Console.WriteLine(e);
                return 0;
            }
        }
    
    
     class USBDeviceInfo
    {
        public USBDeviceInfo(string deviceID, string Description, string location)
        {
            this.DeviceID = deviceID;
            this.Desc = Description;
            this.Location = location;
            
           
        }
        public string DeviceID   { get;}
        public string  Desc      { get;}
        public string Location   { get;}
    }
    

    I am using this Method to take the slot you are asking for. In fact I take the slot of the last plugged in USB due to the requirements I have. You can just debug and see the content of the class USBDeviceInfo and then use it for your own purpose.

提交回复
热议问题