如何更快地使用 readbyte 函数

How can I use readbyte function faster

我在 C# 中使用串口,​​我的代码是这样的:

FileStream MyFile = new FileStream(strFileDestination, FileMode.Append);
BinaryWriter bwFile = new BinaryWriter(MyFile);
bwFile.Write(serialPort1.ReadExisting());
bwFile.Close();
MyFile.Close();

当我使用

bwFile.Write(serialPort1.ReadByte());

而不是

bwFile.Write(serialPort1.ReadExisting());

,写入文件的速度从大约 130 KB/s 降低到 28 KB/s 当我使用

bwFile.Write((byte)serialPort1.ReadByte());

,写入速度下降到 7 KB/s。 我想知道如何像第三个命令一样写入文件并获得速度 130 KB/s.

有没有想过简单的用流来写数据?我认为您实际上并没有使用 BinaryWriter 提供的额外功能 Stream.Write。

只需调用 CopyTo() 方法

Stream destination = new FileStream(...)
MyFile.CopyTo(destination);

在后台调用以下代码:

byte[] buffer = new byte[bufferSize];
int read;
while ((read = serialPort1.Read(buffer, 0, buffer.Length)) != 0)
{
    destination.Write(buffer, 0, read);
}

查看此 post 了解更多信息: