简体   繁体   中英

EndOfStreamException with simple BinaryWriter and BinaryReader

I'm using the following code:

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

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

However I'm getting the following exception:

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

Before reading, binaryReader.BaseStream.Length is bigger than 0, however binaryReader.PeekChar() returns -1.

What am I doing wrong?

After you have written to the stream, the position of the stream will be at the length of whatever you wrote to it.

In order to read from it directly after writing to it, you must reset the position of the stream:

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

Will result in the original "Hello" written to the stream being assigned to msg .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM