C#SerialPort类用法

这个问题的灵感来自于这里的问题和答案: 使用C#的SerialPort类将命令传递到Comm端口

问题本身回答了我遇到的一些问题,但为我提出了一些其他问题。 演示中的答案如下:

var serialPort = new SerialPort("COM1", 9600); serialPort.Write("UUT_SEND \"REMS\\n\" \n"); 

用于基本串口使用。 另请注意: 要获得任何响应,您必须挂钩DataReceived事件。

我的问题如下。 我是否必须使用DataReceived event还是可以使用serialPort.ReadLineserialPort.ReadLine的确切function是什么? 我还需要在我的应用程序中使用serialPort.Open()serialPort.Close()吗?

您可以在MSDN文档中找到有关属性和用法的很好的描述,这是一个小例子:

 void OpenConnection() { //Create new serialport _serialPort = new SerialPort("COM8"); //Make sure we are notified if data is send back to use _serialPort.DataReceived += _serialPort_DataReceived; //Open the port _serialPort.Open(); //Write to the port _serialPort.Write("UUT_SEND \"REMS\\n\" \n"); } void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { //Read all existing bytes var received = _serialPort.ReadExisting(); } void CloseConnectionOrExitAppliction() { //Close the port when we are done _serialPort.Close(); }