Search code examples
c#arraysstringbuilder

Equivalent of StringBuilder for byte arrays


This is a simple one, and one that I thought would have been answered. I did try to find an answer on here, but didn't come up with anything - so apologies if there is something I have missed.

Anyway, is there an equivalent of StringBuilder but for byte arrays?

I'm not bothered about all the different overloads of Append() - but I'd like to see Append(byte) and Append(byte[]).

Is there anything around or is it roll-your-own time?


Solution

  • Would MemoryStream work for you? The interface might not be quite as convenient, but it offers a simple way to append bytes, and when you are done you can get the contents as a byte[] by calling ToArray().

    A more StringBuilder-like interface could probably be achieved by making an extension method.

    Update
    Extension methods could look like this:

    public static class MemoryStreamExtensions
    {
        public static void Append(this MemoryStream stream, byte value)
        {
            stream.Append(new[] { value });
        }
    
        public static void Append(this MemoryStream stream, byte[] values)
        {
            stream.Write(values, 0, values.Length);
        }
    }
    

    Usage:

    MemoryStream stream = new MemoryStream();
    stream.Append(67);
    stream.Append(new byte[] { 68, 69 });
    byte[] data = stream.ToArray();  // gets an array with bytes 67, 68 and 69