问题描述
我正在使用 Visual Studio 2010 并使用 C# (.NET 3.5) 进行编程.
I am using Visual Studio 2010 and programing in C# (.NET 3.5).
我想从 COM10 写入/读取数据.
I want to write/read data from COM10.
这是一个简单的代码:
static void Main(string[] args)
{
String Portname = String.Empty;
/* List out all COM ports present on the computer. */
foreach (string ports in SerialPort.GetPortNames())
{
Console.WriteLine(ports);
/* If COM10 exists, copy the name for further use. */
if (ports == "COM10")
{
Portname = ports; //I also tried this: "\\.\\COM10";
}
}
/* If COM10 not found, return */
if (Portname == String.Empty)
{
Console.WriteLine("Exiting");
return;
}
SerialPort Port = new SerialPort(Portname,
9600, // Baudrate
Parity.None, //Parity
8, //DataBits
StopBits.One); //Stop Bits
Port.Open();
for (int count = 0; count < 5; count++)
{
Port.WriteLine("\nHello");
}
Port.Close();
while (true);
}
每当我在 SerialPort Port = new SerialPort(Portname,9600,.....);
中使用 Portname
作为COM10"时,它都会给出一个错误为
Whenever I use Portname
as "COM10" in SerialPort Port = new SerialPort(Portname,9600,.....);
, it gives an error as
端口'COM10'不存在
在Port.Open()
上,如果COM10不存在,它甚至不应该到达命令Port.Open()
.
On Port.Open()
, it should not even reach to command Port.Open()
if COM10 doesn't exist.
另一种方式,我尝试将 Portname 设为\.\COM10".它给出了一个错误
Another way, I tried Portname as "\.\COM10". It gives an error as
给定的端口名称不以 COM/com 开头或未解析为有效的串行端口.
任何大于 COM9 的端口号都会发生这种情况.
This happens with any port number greater than COM9.
有出路吗?
推荐答案
不能打开大于 10 的串口是因为 FCL SerialPort 实现如下示例:
The reason why you can't open a serial port greater than 10 is because FCL SerialPort implemented like in the following sample:
[MonitoringDescription("PortName")]
[Browsable(true)]
[DefaultValue("COM1")]
public string PortName
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this.portName;
}
set
{
if (value == null)
throw new ArgumentNullException("PortName");
if (value.Length == 0)
throw new ArgumentException(SR.GetString("PortNameEmpty_String"), "PortName");
if (value.StartsWith("\\\\", StringComparison.Ordinal))
throw new ArgumentException(SR.GetString("Arg_SecurityException"), "PortName");
if (this.IsOpen)
throw new InvalidOperationException(SR.GetString("Cant_be_set_when_open", new object[1]
{
(object) "PortName"
}));
else
this.portName = value;
}
}
如您所见,标准 SerialPort 不允许您在端口名称中使用 \\.\ 符号.我不知道他们为什么这样做.使用 \\.\ 符号,可以打开大于 10 的端口.因此,唯一的方法是实现您自己的 SerialPort 组件.
As you see, standard SerialPort does not allow you to use \\.\ notation in the port name. And I don't know why they did this. With \\.\ notation, ports greater than 10 can be opened. So, the only way is to implement your own SerialPort component.
这篇关于在 C# 中访问 COM10 或更大的端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!