Writing to then reading from a MemoryStream

前端 未结 4 464
终归单人心
终归单人心 2020-11-28 09:09

I\'m using DataContractJsonSerializer, which likes to output to a Stream. I want to top-and-tail the outputs of the serializer so I was using a StreamWriter to

4条回答
  •  有刺的猬
    2020-11-28 09:37

    To access the content of a MemoryStream after it has been closed use the ToArray() or GetBuffer() methods. The following code demonstrates how to get the content of the memory buffer as a UTF8 encoded string.

    byte[] buff = stream.ToArray(); 
    return Encoding.UTF8.GetString(buff,0,buff.Length);
    

    Note: ToArray() is simpler to use than GetBuffer() because ToArray() returns the exact length of the stream, rather than the buffer size (which might be larger than the stream content). ToArray() makes a copy of the bytes.

    Note: GetBuffer() is more performant than ToArray(), as it doesn't make a copy of the bytes. You do need to take care about possible undefined trailing bytes at the end of the buffer by considering the stream length rather than the buffer size. Using GetBuffer() is strongly advised if stream size is larger than 80000 bytes because the ToArray copy would be allocated on the Large Object Heap where it's lifetime can become problematic.

    It is also possible to clone the original MemoryStream as follows, to facilitate accessing it via a StreamReader e.g.

    using (MemoryStream readStream = new MemoryStream(stream.ToArray()))
    {
    ...
    }
    

    The ideal solution is to access the original MemoryStream before it has been closed, if possible.

提交回复
热议问题