C # BinaryReader.Read () gets garbage to start with

I am trying to understand what I am doing wrong here. I am trying to use Binary Reader to make it easier to get the initial four bytes from the stream to an Int32 value that tells me how long the rest of the data is expected.

static void Main(string[] args) { MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); string s = "Imagine this is a very very long string."; writer.Write(s.Length); writer.Write(s); writer.Flush(); BinaryReader reader = new BinaryReader(stream); reader.BaseStream.Seek(0, SeekOrigin.Begin); char[] aChars = new char[reader.ReadInt32()]; reader.Read(aChars, 0, aChars.Length); Console.WriteLine(new string(aChars)); } 

The output should be input, but I get it (note that the first character changes from line to line)

(Imagine this is a very long line

Can someone explain to me what I'm doing wrong? Ideally, the second read will continue until the total read bytes are equal to the value of the first four bytes. This code is just a simplification to show the problem I am facing. The flow position seems to be correct (4), but it seems that it starts to count by 2.

+6
c # memorystream binaryreader
source share
1 answer

BinaryWriter.Write (String) writes a string with a length prefix to this stream. This means that it first writes the length of the string to the stream, and then the string using some encoding. The length is encoded seven bits at a time, and not as a 32-bit integer.

If you want to read from a stream, you must use BinaryReader.ReadString , which reads a string with a prefix of length from the stream.

+8
source share

All Articles