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.
BinaryWriter.Write(String) writes a length-prefixed string to this stream. This means 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, not as 32-bit integer.
If you want to read from the stream, you should use BinaryReader.ReadString, which reads a length-prefixed string from the stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With