Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 255
Mugen Avatar asked Jul 08 '26 07:07

Mugen


1 Answers

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.

like image 76
aevitas Avatar answered Jul 11 '26 01:07

aevitas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!