我可以针对以下 C# 串行端口错误做些什么



如果我运行我用SharpDevelop创建的以下代码:

        SerialPort serial = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
        void sendMsg_Click(object sender, EventArgs e)
        {
            serial.Open();
            serial.WriteLine(textBox1.Text);
            serial.Write(new byte[] {0x0A, 0xE2, 0xFF}, 0, 3);
            serial.Close();
        }

下面是执行代码时出现的异常:

例外情况如下:

System.IO.IOException: Falscher Parameter.
bei System.IO.Ports.InternalResources.WinIOError
bei System.IO.Ports.SerialStream.EndWrite
bei System.IO.Ports.SerialStream.Write
bei System.IO.Ports.SerialPort.Write
bei System.IO.Ports.SerialPort.WriteLine
bei Chat_via_RS232.MainForm.sendMsg_Click in c:UsersadminDocumentsSharpDevelop ProjectsLatias.eu ITChat via RS232MainForm.cs:Zeile 35
bei System.Windows.Forms.Control.OnClick
bei System.Windows.Forms.Button.OnClick
bei System.Windows.Forms.Button.OnMouseUp
bei System.Windows.Forms.Control.WmMouseUp
bei System.Windows.Forms.Control.WndProc
bei System.Windows.Forms.ButtonBase.WndProc
bei System.Windows.Forms.Button.WndProc
bei System.Windows.Forms.Control.ControlNativeWindow.OnMessage
bei System.Windows.Forms.Control.ControlNativeWindow.WndProc
bei System.Windows.Forms.NativeWindow.DebuggableCallback
bei System.Windows.Forms.Application.ComponentManager.FPushMessageLoop
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoop
bei System.Windows.Forms.Application.Run
bei Chat_via_RS232.Program.Main in c:UsersadminDocumentsSharpDevelop ProjectsLatias.eu ITChat via RS232Program.cs:Zeile 24

有人可以帮我吗?

问候

拉拉

错误位于此行:

serial.WriteLine(textBox1.Text)

您的异常报告显示正在引发IOException,但是WriteLine的文档未将IOException列为记录的异常:https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.writeline(v=vs.110).aspx - 可能还有其他问题。

SerialPort.Open的文档指出,如果端口不可用,则会在那里引发异常(https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open(v=vs.110).aspx),但这不会发生在您的程序中。我怀疑可能有无效值传递到 WriteLine 函数中。如果将Write( Byte[] )呼叫移至WriteLine呼叫之前,会发生什么情况?

最新更新