开发者

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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜