C# SerialPort#Open() 方法由于端口名称而引发 ArgumentException?

C# SerialPort#Open() method throws ArgumentException because of port name?(C# SerialPort#Open() 方法由于端口名称而引发 ArgumentException?)

本文介绍了C# SerialPort#Open() 方法由于端口名称而引发 ArgumentException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的本地机器上,

  • Windows XP
  • 端口(COM 和 LPT)
    • COM3
    • RIM 虚拟串行端口 v2 (COM4)
    • RIM 虚拟串行端口 v2 (COM5)

    以下代码,

    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();
            }
        }
    }
    

    会抛出以下ArgumentException

    也就是说,

    给定的端口名称不以 COM/com 开头或不解析为一个有效的串口.

    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?

    推荐答案

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

    似乎问题在于那些 COM 端口被映射到其他东西并给出了这个奇怪的错误作为响应.

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

    我遇到了完全相同的问题.我发现我有一个 Windows 打印机设置来使用相同的端口.一旦我更改了打印机设置中的端口,SerialPort.Open() 就起作用了.

    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.

    这篇关于C# SerialPort#Open() 方法由于端口名称而引发 ArgumentException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C# SerialPort#Open() 方法由于端口名称而引发 ArgumentException?

基础教程推荐