I am trying to figure out what I am doing wrong here. I am attempting to use a Binary Reader to ease getting an initial four bytes from a stream into an Int32 value that tells me how long the rest of the data is to be 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 the input, but I get this (Note that the first character changes from string to string)
(Imagine this is a very very long string
Can someone explain to me what I am doing wrong? Ideally the second read would continue until the total read bytes was equal to the value of the first four bytes.. this code is just a simplification to show the problem I am running into. The position of the stream seems correct (4) but it almost seems like it starts reading at 2.