Personally, I would not use BinaryFormatter
for this purpose - it is implementation specific and overly expensive. I would be tempted to (one of):
1: use BinaryWriter
/ BinaryReader
to do it manually (but note that this is easy to interpret from any API):
// note I've used arrays in the example; lists are identical
int[] data = { 1, 2, 3, 4, 5 };
byte[] raw;
using (var ms = new MemoryStream())
using (var writer = new BinaryWriter(ms))
{
writer.Write(data.Length);
foreach(int i in data) {
writer.Write(i);
}
writer.Close();
raw = ms.ToArray();
}
// read it back
using (var ms = new MemoryStream(raw))
using (var reader = new BinaryReader(ms))
{
int count = reader.ReadInt32();
data = new int[count];
for (int i = 0; i < count; i++)
{
data[i] = reader.ReadInt32();
}
}
or 2: use an implemenation-independent serialization format, such as protobuf; here I'm using protobuf-net
int[] data = { 1, 2, 3, 4, 5 };
byte[] raw;
using (var ms = new MemoryStream()) {
Serializer.Serialize(ms, data);
raw = ms.ToArray();
}
// read it back
using (var ms = new MemoryStream(raw)) {
data = Serializer.Deserialize<int[]>(ms);
}
Note that (1) uses 24 bytes for the example (6 * 4 bytes); (2) uses 10 bytes (in part because the numbers are simple, but actually protobuf has some tricks (such as "packed" data) that we aren't even using here).