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.
c # memorystream binaryreader
James
source share