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 StringBu开发者_高级运维ilder 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?
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
The MemoryStream
approach is good, but if you want to have StringBuilder-like behavior add a BinaryWriter
. BinaryWriter provides all the Write overrides you could want.
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
writer.Write((byte)67);
writer.Write(new byte[] { 68, 69 });
Probably List<byte>
:
var byteList = new List<byte>();
byteList.Add(42);
byteList.AddRange(new byte[] { 1, 2, 3 });
List<byte>
Then when you want it as an array you can call ToArray()
using System;
using System.IO;
public static class MemoryStreams
{
public static MemoryStream Append(
this MemoryStream stream
, byte value
, out bool done)
{
try
{
stream.WriteByte(value);
done = true;
}
catch { done = false; }
return stream;
}
public static MemoryStream Append(
this MemoryStream stream
, byte[] value
, out bool done
, uint offset = 0
, Nullable<uint> count = null)
{
try
{
var rLenth = (uint)((value == null) ? 0 : value.Length);
var rOffset = unchecked((int)(offset & 0x7FFFFFFF));
var rCount = unchecked((int)((count ?? rLenth) & 0x7FFFFFFF));
stream.Write(value, rOffset, rCount);
done = true;
}
catch { done = false; }
return stream;
}
}
Look at this project at codeproject. It's just one class that implements the solution with a MemoryStream as suggested in other answers.
精彩评论