我正在使用以下代码:
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()
返回-1。我究竟做错了什么?
最佳答案
写入流之后,流的位置将等于您写入流的长度。
为了在写入后直接从中读取,必须重置流的位置:
binaryWriter.Write("Hello");
binaryWriter.BaseStream.Position = 0;
var msg = binaryReader.ReadString();
将导致写入流的原始“ Hello”被分配给
msg
。关于c# - 具有简单BinaryWriter和BinaryReader的EndOfStreamException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29766572/