Why GetPortNames method returns nothing?

5.9k Views Asked by At

I am trying to send an SMS from computer to cell phone. The first step: get all com ports to use it. I used this code, but no benefit:

private void Form1_Load(object sender, EventArgs e)
{
    string[] Ports = SerialPort.GetPortNames();
    foreach (string prt in Ports)
    {
        comboBox1.Items.Add(prt);
    }
}

It returns nothing. What can I do?

2

There are 2 best solutions below

1
On

I just ran the following code on my PC and it returns "COM1":

        string[] ports = SerialPort.GetPortNames();

        Console.WriteLine("The following serial ports were found:");
        foreach(string port in ports)
        {
            Console.WriteLine(port);
        }

        Console.ReadLine();

So, it's either permissions or you don't have any Serial ports. Or perhaps your registry is corrupt?

Note:

The port names are obtained from the system registry (for example, HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM). If the registry contains stale or otherwise incorrect data then the GetPortNames method will return incorrect data.

Ref: SerialPort.GetPortNames

0
On

I had the same issue at first. Then realized that I didn't connect any device to my PC which identify themselves as a serial port (either via USB or any other physical port). It displayed accurately when I connected a device (a USB based PIC programmer in my case). Please check if your device is properly detected.