Can a byte[] buffer for a MemoryStream have variable size?

a 夏天 提交于 2019-12-22 11:21:37

问题


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?


回答1:


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();
}



回答2:


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.



来源:https://stackoverflow.com/questions/12309107/can-a-byte-buffer-for-a-memorystream-have-variable-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!