Serialize Buffer Length

A

Andrew Robinson

I am using the folllowing code to serialize a [serializable] object to a
byte array (byte[]). It works fine, but my resulting array is size is being
rounded up to the next largest 32768 boundary. How can I complete the
serialization without incurring the extra bytes.

I know there is a simple answer....


Thanks,


MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, myObject);
byte[] b = memoryStream.GetBuffer();
 
A

Andrew Robinson

Ok, there must be a better way than this:

MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, myObject);
b = new byte[memoryStream.Length];
Array.Copy(memoryStream.GetBuffer(), b, memoryStream.Length);

thanks,
 
A

Andrew Robinson

Ok, I think I have answered my own question here:


using (MemoryStream memoryStream = new MemoryStream()) {
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, myObject);
b = memoryStream.ToArray();
memoryStream.Close();
}



Andrew Robinson said:
Ok, there must be a better way than this:

MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, myObject);
b = new byte[memoryStream.Length];
Array.Copy(memoryStream.GetBuffer(), b, memoryStream.Length);

thanks,


Andrew Robinson said:
I am using the folllowing code to serialize a [serializable] object to a
byte array (byte[]). It works fine, but my resulting array is size is
being rounded up to the next largest 32768 boundary. How can I complete
the serialization without incurring the extra bytes.

I know there is a simple answer....


Thanks,


MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, myObject);
byte[] b = memoryStream.GetBuffer();
 
J

Jon Skeet [C# MVP]

Andrew Robinson said:
Ok, I think I have answered my own question here:


using (MemoryStream memoryStream = new MemoryStream()) {
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, myObject);
b = memoryStream.ToArray();
memoryStream.Close();
}

Exactly. Note that you don't need to call Close() - you're using a
"using" statement which will call Dispose on your MemoryStream already.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top