views:

292

answers:

1

Hi i am new to c#. I am trying to understand the usage of .Net MemoryStream class. I need to use the store some temporary dynamic length binary data as the stream is busy. So i allocate a memory stream and temporarily write that data to it. When my stream gets free i read all the data from the memorystream and write the data to it. I do this by setting the position pointer to 0

i.e mDataBuffer.Position=0;

However it seems that the memorystream class doesn't discard data once its read. So next time i get the same data as before. To confirm i wrote this sample program

        MemoryStream ms = new MemoryStream();
        ms.WriteByte((byte)1);
        ms.Position = 0;
        Console.WriteLine(ms.ReadByte());
        ms.WriteByte((byte)4);
        ms.Position = 0;
        Console.WriteLine(ms.ReadByte());

and to my surprise the output was (1,1) although i was expecting an output of (1,4).

I am really puzzled by this behavior of memorystream. Can anyone shed some light. Also if this is the normal behaviour then how can i delete past data from the stream.

Thanks in advance, vaibhav

+1  A: 

Your code can be translated to this: * Create object * Write 1 at position 0 * Read at position 0 and output (1) * Write 4 at position 1 * Read at position 0 and output (1)

You can fix it by inserting ms.Position=0 above the ms.writebyte((byte)4) line.

Lars D