Click here to Skip to main content
15,562,816 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
So here's the thing I have this program that does stuff for CAN, now the CAN messages are being sent to the end Application via the Serial Port, sometimes however it gets stuck when trying to detect the Com Port.

The application operates as follows, First Detect the Com Port( this is where it gets stuck ), then do the actual connection and the process the Data.
To solve the problem, I usually have to pull out the usb to serial cable then restart the App, this is not ideal as this software is going Live soon.

One of the reasons it could be going haywire is that the CAN codes are being blasted into the serial port (This cannot be Stopped). Is it for that brief moment that the serial port is open for, the data cannot be processed and it just freezes, do I need to delay a bit or discard data??
So here's the code :

for (int COM_Attempt = 1; COM_Attempt <= 50; COM_Attempt++)
              string str_COM_Attempt = Convert.ToString(COM_Attempt);

              SP.PortName = "COM" + str_COM_Attempt;
              SP.BaudRate = 9600;

                  //Add port to the list of available ones
                  PortList.Items.Add("COM" + str_COM_Attempt);


          //Display the first entry
          PortList.Text = PortList.Items[0].ToString();
Updated 13-Mar-21 11:16am

1 solution

Take a look at SerialPort.GetPortNames[^]

It is a static function, that give you all serial ports on the computer.

// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();

// Add each port to the list.
foreach(string port in ports)
  PortList.Items.Add("COM" + port);
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900