Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Writer returns byte array of null

I'm working with the MRIM (Mail.Ru Agent) protocol. MRIM is a binary protocol, so in order to make the data binary, I'm using the BinaryWriter class. Here's the code:

    private byte[] CreateMrimPacket(ulong message) 
    { 
       byte[] binaryData; 
        using (MemoryStream ms = new MemoryStream()) 
        { 
            using (BinaryWriter bw = new BinaryWriter(ms)) 
            { 
                bw.Write(CS_MAGIC); //CS_MAGIC is a constant that doesn't equal 0
                bw.Write(PROTO_VERSION); //Same thing
                bw.Write((ulong)SeqCounter); 
                bw.Write(message); 
                bw.Write((ulong)0); 
                bw.Write((ulong)0); 
                bw.Write((ulong)0); 
                bw.Write((ulong)0); 
                bw.Write((ulong)0); 
                bw.Write((ulong)0); 
                bw.Write((ulong)0); 
                binaryData = new byte[ms.Length]; 
                ms.Read(binaryData, 0, binaryData.Length); 
            } 
        } 
        return binaryData; 
    } 

This function returns byte array but all the values are 0.
Please, help me to solve this problem.
Thanks in advance

like image 207
Cracker Avatar asked Jul 15 '26 00:07

Cracker


1 Answers

You're writing to the stream, leaving it at the end of the data you've written, and then reading from it. There's no data at the current position!

You could use ms.Position = 0; before reading... but fortunately, it's easier than you're making it anyway... just use:

return ms.ToArray();

MemoryStream.ToArray returns all the data in the stream, regardless of the current position (and also regardless of whether the stream is closed or not).

like image 111
Jon Skeet Avatar answered Jul 16 '26 12:07

Jon Skeet



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!