有没有办法直接将串口传入数据保存到文件中?

时间:2013-08-27 13:06:08

标签: c# serial-port bytearray bytebuffer

我需要将整个传入的串口数据保存到文件中。有些人建议使用File.WriteAllBytes,但它会获取创建的字节数组的所有空索引。

        Array.Resize(ref Read_Data2, Read_Data2.Length + incoming.Length);

        public void SaveData(byte[] incoming)
        {
            for (int i = 0; i < incoming.Length; i++)
            {
                Read_Data2[x] = incoming[i];
                ++x;
            }


            File.WriteAllBytes("C:\\Test3.text", Read_Data2);
        }

我使用该方法将所有传入的字节保存到Read_Data2中,但我觉得有些不对劲。如前所述,它保存了字节数组的空索引。我如何改进这个或有没有更好的方法将传入的串口数据保存到文件中?

1 个答案:

答案 0 :(得分:-1)

 private void mySerialPort_DataReceived(System.Object sender, System.IO.Ports.SerialDataReceivedEventArgs e)

{

                SerialPort spL = (SerialPort)sender;
                byte[] bytesToRec = new byte[spL.byteToRead];
                Int64 bytes = spL.Read(bytesToRec, 0, bytesToRec.Length);
                navSerialPort.DiscardInBuffer();
                navSerialPort.DiscardOutBuffer();
                string filepath = @"" + textBox1.Text + "\\" + "KMTU_" +DateTime.Now.ToString("MMM-d-yyyy") + ".hex";
                FileStream LogFile = new FileStream(filepath, FileMode.Create);
                LogFile.Write(bytesToRec, 0, bytesToRec.Length);
                 LogFile.Close();
}