I'm serializing an object to a byte[]
using MemoryStream
:
byte[] serialized = new byte[1000];
using (MemoryStream stream = new MemoryStream(serialized))
using (TextWriter textWriter = new StreamWriter(stream))
serializer.Serialize(textWriter, stuffToSerialize);
is there any way I can set 'serialized'
to grow according to the size of the stuffToSerialize
?
The parameterless constructor new MemoryStream()
uses one.
Then serialise into it, and then when you need the byte[]
call ToArray()
which creates a copy of whatever length of the buffer was actually used (the internal buffer will generally have some growing space at any point, and that's normally not desirable, ToArray()
gives you what you actually care about).
At the end of the following code, it will have the same effect as your code, were you able to predict the correct size:
byte[] serialized;
using (MemoryStream stream = new MemoryStream())
{
using (TextWriter textWriter = new StreamWriter(stream))
{
serializer.Serialize(textWriter, stuffToSerialize);
}
// Note: you can even call stream.Close here is you are paranoid enough
// - ToArray/GetBuffer work on disposed MemoryStream objects.
serialized = stream.ToArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With