CodeJoy CodeJoy - 22 days ago 6x
C# Question

Append bytes to MemoryStream without moving the position

I'm trying to append data to a MemoryStream with the Write(); Method
But that Also moves the Position. I know I can change the Position manually.
But is there a way to append data to a MemoryStream without moving the Position

using (MemoryStream stream = new MemoryStream())
using (BinaryReader reader = new BinaryReader(stream))
byte[] data = new byte[20];
Random rand = new Random();

stream.Write(data, 0, 20);
Console.WriteLine(reader.ReadInt32());//Pointer = 20 here



No, a MemoryStream does not have any functionality to do that on it's own. For a stream, this is also the logical behavior.

But that also means that there is nothing wrong if you are doing this yourself. If your intention is to have some kind of nice way of reusing this functionality, I'd recommend writing a simple extension method for MemoryStream:

public static class Extensions
    public static void WriteAndResetPosition(this MemoryStream stream, byte[] data, int offset, int count)
        stream.Write(data, offset, count);
        stream.Position -= count;

That's brain compiled code :), so take it with a grain of salt. After that, you can use it like:

stream.WriteAndResetPosition(data, 0, 20);