0

I have a code which displays the list of ports where a connection is made. For example, if I have two USB points in the laptop and only one is being used with a USB Cable attached, it should show only the one where the USB Cable is attached. This code used to work perfectly till sometime back, but now it is showing all the ports.

What could be the solution?

Below is my code.

try
        {

                string[] ports = SerialPort.GetPortNames();
                comboBox1.Items.AddRange(ports);
                comboBox1.SelectedIndex = 0;
                button2.Enabled = false;
            
        }
        catch
        {
            MessageBox.Show("Error.", "No Port detected.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            comboBox1.Text = "";
        }
  • 1
    Doesn't look like there is a filter for "ports in use, only". It also does not get USB but Serial. Which leads me to the conclusion that you probably had a device attached that installed a driver which set up a "serial port emulation" which is quite a common thing for USB devices. Then you have a "new" COM port. Even if you detach that device, the port will still be there. – Fildor Jun 17 '21 at 06:34
  • If, actually, this is less about ports but about attached _devices_, you may want to look for actually attached USB devices and look up their Serial Ports. – Fildor Jun 17 '21 at 06:38
  • Maybe also have a deepdive into https://stackoverflow.com/questions/3331043/get-list-of-connected-usb-devices – Fildor Jun 17 '21 at 06:41
  • Like the mouse check when starting Windows in the old days, try opening the list of acquired port names in order, and if you can open it, mark it as unused and close it immediately. – kunif Jun 17 '21 at 07:36
  • @Fildor I have an instrument sending data to my computer through a serial-USB convertor. Ofcourse more USBs may or may not be plugged in to the same computer while this instrument is connected. Ideally I would like a code which identifies by name all devices plugged in so the application user can chose to a decision about which device to connect and Use, or perhaps we can filter for the device name and make sure only our instrument gets connected. I went through the link you provided, the codes are available only for console applications. I am a beginner in coding, can you help please. – Dr. Strange Jul 24 '21 at 17:53

0 Answers0