Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set a fixed length for MemoryStream?

Tags:

c#

.net

I'm extending BinaryWriter using a MemoryStream.

public class PacketWriter : BinaryWriter
{
    public PacketWriter(Opcode op) : base(CreateStream(op))
    {
        this.Write((ushort)op);
    }

    private static MemoryStream CreateStream(Opcode op) {
        return new MemoryStream(PacketSizes.Get(op));
    }

    public WriteCustomThing() {
        // Validate that MemoryStream has space?
        // Do all the stuff
    }
}

Ideally, I want to use write using PacketWriter as long as there is space available (which is already defined in PacketSizes). If there isn't space available, I want an exception thrown. It seems like MemoryStream just dynamically allocates more space if you write over capacity, but I want a fixed capacity. Can I achieve this without needing to check the length every time? The only solution I thought of so far was to override all the Write methods of BinaryWriter and compare lengths, but this is annoying.

like image 399
Ci3 Avatar asked Oct 19 '25 10:10

Ci3


1 Answers

Just provide a buffer of the desired size to write into:

using System;
using System.IO;

class Test
{
    static void Main()
    {
        var buffer = new byte[3];
        var stream = new MemoryStream(buffer);
        stream.WriteByte(1);
        stream.WriteByte(2);
        stream.WriteByte(3);
        Console.WriteLine("Three successful writes");
        stream.WriteByte(4); // This throws
        Console.WriteLine("Four successful writes??");
    }
}

This is documented behavior:

Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array.

like image 189
Jon Skeet Avatar answered Oct 21 '25 01:10

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!