Got a System.Management.Managementexception: 'Invalid Query' error while trying to get COM port descriptors in Visual Studio 2022

Got a System.Management.Managementexception: 'Invalid Query' error while trying to get COM port descriptors in Visual Studio 2022

Using Visual-Studio 2022 Community on Windows 10, following a Read more in C# in which a 'Windows Forms App(.NET Framework)' project lists all COM ports, and their descriptions, as would be seen/found in Windows Device Manager. Device Manager - Ports(COM & LPT)

In the forms app, there's a textbox that displays the list of COM ports, and their descriptions, when launched. And a button to exit the program too.

When I build and then start the debugger, an error is thrown in Visual Studio specific to this line of code (the part that gathers the desriptions of the COM port): var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString()); The error shown is this:

Exception Unhandled System.Management.ManagementException: 'Invalid Query'

Don't know why this error is thrown, as the code is what's found in the tutorial. Moreover, don't know how to diagnose and fix the issue.

The tutorial code is this:

using System;
using System.Collections.Generic;
using System.Data;
using System.IO.Ports;
using System.Linq;
using System.Management;
using System.Windows.Forms;

namespace Device_Manager_COMS_searcher
{
    public partial class Form1 : Form
    {
        List<string> portnames = new List<string>();

        public Form1()
        {
            InitializeComponent();

            portnames = GetPorts();
            foreach (string port in portnames)
            {
                textBox1.AppendText(port + "\r\n");
            }


        }

        public List<string> GetPorts()
        {
            // This searches all the properties of the Plug and Play devices
            // (using "Win32_PnPEntity"). The "caption" is the text description of
            // the COM port object.

            // Search all Plug n Play entities where the Caption has "(COM" plus
            // any number of leading and lagging characters.
            using (var searcher = new ManagementObjectSearcher("SELECT * FROM" + "Win32_PnpEntity WHERE Caption like %(COM%'"))
            {
                // This gets the simple port names, such as "COM4"
                string[] portnames = SerialPort.GetPortNames();

                // This gets the caption/description of the found ports *** Throws error: System.Management.Managementexception: 'invalid query ' ***
                var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());

                // Append the description of each port to the corresponding port name
                // and add to the list
                List<string> portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();
                
                return portList;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

In Visual-Studio, I have added the reference "System.Management" via the Reference Manager".

Have also tried adding this same reference via NuGet too. Both haven't fixed the issue.

For sanity, I wanted to see if the program/app could launch and find the COM ports without the descriptions. So I changed the Form design to add one more button "GET COMS", which when clicked would fetch the COM ports and their number only, but not the description. Like this:

using System;
using System.Collections.Generic;
using System.Data;
using System.IO.Ports;
using System.Linq;
using System.Management;
using System.Windows.Forms;

namespace Device_Manager_COMS_searcher
{
    public partial class Form1 : Form
    {
        List<string> portnames = new List<string>();

        public Form1()
        {
            InitializeComponent();
        }

        public List<string> GetPorts()
        {
            // This searches all the properties of the Plug and Play devices
            // (using "Win32_PnPEntity"). The "caption" is the text description of
            // the COM port object.

            // Search all Plug n Play entities where the Caption has "(COM" plus
            // any number of leading and lagging characters.
            using (var searcher = new ManagementObjectSearcher("SELECT * FROM" + "Win32_PnpEntity WHERE Caption like %(COM%'"))
            {
                // This gets the simple port names, such as "COM4"
                string[] portnames = SerialPort.GetPortNames();

                // Append the description of each port to the corresponding port name
                // and add to the list
                List<string> portList = portnames.Select(n => n).ToList();
                
                return portList;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            portnames = GetPorts();
            foreach (string port in portnames)
            {
                textBox1.AppendText(port + "\r\n");
            }

        }
    }
}

When built and the debugger started, it works. I click the "GET COMS" button and it displays the COM ports with stuff plugged in, like this; Working Example minus descriptors for COM ports

But again, if I change the code to the "GetPorts()" section which adds a descriptor, like this:

public List<string> GetPorts()
{
    // This searches all the properties of the Plug and Play devices
    // (using "Win32_PnPEntity"). The "caption" is the text description of
    // the COM port object.

    // Search all Plug n Play entities where the Caption has "(COM" plus
    // any number of leading and lagging characters.
    using (var searcher = new ManagementObjectSearcher("SELECT * FROM" + "Win32_PnpEntity WHERE Caption like %(COM%'"))
    {
        // This gets the simple port names, such as "COM4"
        string[] portnames = SerialPort.GetPortNames();

        // This gets the caption/description of the found ports *** Throws error: System.Management.Managementexception: 'invalid query ' ***
        var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());

        // Append the description of each port to the corresponding port name
        // and add to the list
        List<string> portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();
        
        return portList;
    }
}

I get the error.

Need help to fix, please?

Answer

Your query string has 2 problems: you're missing a leading single quote and a space. The query should look like this:
using (var searcher = new ManagementObjectSearcher("SELECT * FROM " + "Win32_PnpEntity WHERE Caption like %(COM%'"))

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles