C# SerialPort#Open() method throws ArgumentException because of port name?
Asked Answered
B

1

1

On my local machine,

  • Windows XP
  • Ports (COM & LPT)
    • COM3
    • RIM Virtual Serial Port v2 (COM4)
    • RIM Virtual Serial Port v2 (COM5)

the following code,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;

namespace OpenSerialPortTest
{
    class Test
    {
        static void Main(string[] args)
        {
            foreach (String serialPortName in SerialPort.GetPortNames())
            {
                SerialPort serialPort = new SerialPort(serialPortName);
                try
                {
                    serialPort.Open(); // Line 19
                    Console.WriteLine(serialPort.PortName);
                }
                catch (Exception ex1)
                {
                    Console.WriteLine(ex1);
                    try
                    {
                        serialPort.Close();
                    }
                    catch (Exception ex2)
                    {
                        Console.WriteLine(ex2);   
                    }
                }
            }
            Console.ReadLine();
        }
    }
}

will throw the following ArgumentException,

enter image description here

That is,

The given port name does not start with COM/com or does not resolve to a valid serial port.

Does anybody know why this is happening?

Buhler answered 23/7, 2012 at 1:29 Comment(3)
Check if the port is already opened first!Czech
@AhmedGhoneim, IsOpen returns falseBuhler
Cool, so please call serialPort.Close(); before opening it, just try it :)Czech
A
2

have a look at http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/35954173-2eeb-46af-bb3e-86840c6b5484

seems the problem was that those COM ports were mapped to something else and gives this strange error in response.

I had exactly the same problem. I found that I had a windows printer setup to use the same port. As soon as I changed the port in the printers settings, the SerialPort.Open() worked.

Amphibiotic answered 23/7, 2012 at 1:33 Comment(2)
Yes, but I hardcoded it once to COM5 and I was seeing the same problem.Buhler
when I do that, I get COM3, COM4, and COM5.Buhler

© 2022 - 2024 — McMap. All rights reserved.