EndOfStreamException 与简单的 BinaryWriter 和 BinaryReader

EndOfStreamException with simple BinaryWriter and BinaryReader

我正在使用以下代码:

var fileStream = new MemoryStream();
var binaryWriter = new BinaryWriter(fileStream);
var binaryReader = new BinaryReader(fileStream);

binaryWriter.Write("Hello");
var msg = binaryReader.ReadString();

但是我遇到了以下异常:

System.IO.EndOfStreamException: Unable to read beyond the end of the stream.

读取前,binaryReader.BaseStream.Length大于0,然而binaryReader.PeekChar() returns -1.

我做错了什么?

写入流后,流的位置将是您写入的内容的长度。

为了在写入后直接从中读取,您必须重置流的位置:

binaryWriter.Write("Hello");
binaryWriter.BaseStream.Position = 0;
var msg = binaryReader.ReadString();

将导致写入流的原始 "Hello" 分配给 msg