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 use the constructor that takes a provided existing byte[]
buffer, then no, because an array once allocated has a fixed size.
The default constructor, as well as any other constructor that does not accept a byte[]
parameter, will replace the existing buffer with a larger one as needed. Note that this may complicate things if you use GetBuffer()
: if the stream is appended to after calling GetBuffer(), the actual byte[]
backing the stream may be replaced. Also note that when calling GetBuffer()
, the stream data may not begin at index 0 of the returned array!
To get the contents back out, use ToArray()
to get them as a byte array, or WriteTo(Stream)
to pour the contents of the MemoryStream
into another stream.