EndOfStreamException,带有简单的BinaryWriter和BinaryReader

时间:2015-04-21 08:16:33

标签: c# serialization memorystream binaryreader binarywriter

我使用以下代码:

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。

我做错了什么?

1 个答案:

答案 0 :(得分:5)

在您写入流后,流的位置将与您写入的内容的长度相符。

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

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

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