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

C# 有没有办法直接将串口输入数据保存到文件中?,c#,serial-port,bytearray,bytebuffer,C#,Serial Port,Bytearray,Bytebuffer,我需要将所有传入的串行端口数据保存到一个文件中。有些人建议使用File.writealBytes,但它会获取所创建字节数组的所有空索引 Array.Resize(ref Read_Data2, Read_Data2.Length + incoming.Length); public void SaveData(byte[] incoming) { for (int i = 0; i < incoming.Length

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

        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中,但我认为有问题。它保存字节数组的空索引,如我前面所说。如何改进这一点,或者是否有更好的方法将传入的串行端口数据保存到文件中

这是一种简单方便的方法,当数组大小不合适时,它就不再方便了。就像数组在不断调整大小时不再方便一样。所以要么使用列表,要么使用文件流。谢谢你的建议。
 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();
}