C# 如何更快地使用readbyte函数

C# 如何更快地使用readbyte函数,c#,serial-port,binaryfiles,C#,Serial Port,Binaryfiles,我在c#中使用serialport,我的代码如下: FileStream MyFile = new FileStream(strFileDestination, FileMode.Append); BinaryWriter bwFile = new BinaryWriter(MyFile); bwFile.Write(serialPort1.ReadExisting()); bwFile.Close(); MyFile.Close(); 当我使用 bwFile.Write(serialPort

我在c#中使用serialport,我的代码如下:

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((byte)serialPort1.ReadByte());
而不是

bwFile.Write(serialPort1.ReadExisting());
,文件中的写入速度从大约130 KB/s降低到28 KB/s 当我使用

bwFile.Write(serialPort1.ReadByte());
bwFile.Write((byte)serialPort1.ReadByte());
,写入速度降低到7 KB/s。
我想知道如何像第三个命令那样写入文件,并使速度达到130 KB/s。

您是否考虑过简单地使用流来写入数据?我认为您实际上没有使用BinaryWriter在Stream.Write上提供的额外功能

只需调用CopyTo()方法

在引擎盖下调用以下代码:

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

查看这篇文章以了解更多信息:

可能在循环中执行
serialPort1.ReadByte()
?是的。我在循环中使用这个命令。循环是这样的:而Logger==true{/*我发布的代码*/},Logger是一个变量,允许我的程序在文件中写入。按下按钮,记录器将更改为falseThank。我尝试过简单地使用Filestream。但是文件中的数据没有完全接收到。我的意思是,在文件的某个地方,一些数据不是发送者发送到我笔记本电脑的真实数据。顺便说一下,我的笔记本电脑没有任何串行端口,发送到笔记本电脑的设备使用usb电缆,我使用的是虚拟COM。谢谢。我尝试过使用简单的文件流。但是文件中的数据没有完全接收到。我的意思是,在文件的某个地方,一些数据不是发送者发送到我笔记本电脑的真实数据。顺便说一下,我的笔记本电脑没有任何串行端口,发送到笔记本电脑的设备使用usb电缆和虚拟COM。无论如何,我不能使用你上面写的代码。我有编译错误,你能解释一下代码吗。(我的英语不好。如果我的句子有错误,很抱歉。而且我不理解“Which under the hood is calling the following code”这句话的意思)你得到的编译错误是什么?要获得完整的解释,请看我发布的链接,那里有更多的细节。它起作用了。问题是“读”字。当我使用SerialPort1.Read(buffer,0,buffer.length)时,它工作正常。(哪个SerialPort1是我在代码中定义的端口名。)谢谢。很高兴听到这个消息。如果你能将答案标记为解决方案,那就太好了。谢谢