prattom
prattom

Reputation: 1753

Identifying USB to serial port given USB VID and PID using WMI query

I am using WMI query to detect USB to serial port but the problem is that in windows 7 the application takes long time to start while in windows xp it is working fine. I am using wmi query in following way

ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPDevice");
            foreach (ManagementObject queryObj in searcher.Get())
            {
                if (queryObj["SameElement"].ToString().Contains("SerialPort"))
                {
                    //do something
                 }
             }

According to my reasoning it is happening due to large number of Pnp Devices and querying for serial port from that list. I tried using Win32_SerialPort but it working in windows xp while on my laptop(windows 7) it shows message not supported even though their are virtual serial port and USB to serial ports. It doesn't work even from administrator account. MSSerial_PortName also doesn't work on my laptop(windows7). Thus is their any way to make my application start faster in windows 7 using WMI query?

Upvotes: 1

Views: 2756

Answers (1)

user38723
user38723

Reputation: 39

Win32_PnPDevice takes a long time MSSerial_PortName works on my Win 7 laptop. Try this (should work, modified from a program I had):

try
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName");
        foreach (ManagementObject queryObj in searcher.Get())
        {
            serialPort = new SerialPort(queryObj["PortName"].ToString(), 115200, Parity.None, 8, StopBits.One);//change parameters
            //If the serial port's instance name contains USB
            //it must be a USB to serial device
            if (queryObj["InstanceName"].ToString().Contains("USB"))//if you have a VID or PID name then this should not be nessesery
            {
                //should get serial to usb adapters
                try
                {
                    serialPort.Open();
                    if (queryObj["InstanceName"].ToString().Contains(VID_or_PID))
                    {
                        //do sth
                    }
                    serialPort.Close();
                }
                catch (Exception ex)
                {
                    //exception handling
                }
            }

        }
    }
    catch (ManagementException ex)
    {
        //write("Querying for WMI data. Exception raised(" + ex.Message + "): " + ex);
    }

Upvotes: 1

Related Questions