【问题标题】:Is there any way to directly save serial port incoming data into file?有没有办法直接将串口传入的数据保存到文件中?
【发布时间】:2013-08-27 13:06:07
【问题描述】:

我需要将整个传入的串行端口数据保存到一个文件中。有人建议使用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 中,但我认为有问题。正如我之前所说,它保存了字节数组的空索引。我该如何改善这一点,或者有没有更好的方法将传入的串行端口数据保存到文件中?

【问题讨论】:

  • 这是一种简单方便的方法,当您的数组大小不合适时,它就不再方便了。就像数组在你不断地调整它的大小时不再方便一样。所以要么使用List&lt;byte&gt;,要么使用FileStream。
  • 感谢汉斯的建议。

标签: c# serial-port bytearray bytebuffer


【解决方案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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2020-01-18
    相关资源
    最近更新 更多