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

假如想象 提交于 2019-12-06 10:05:01

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.

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