Is it possible to get length of closed memory stream?
Asked Answered
L

1

3

I am trying to use GZipStream with MemoryStream. I write all bytes I need and then close gzip stream so after that I need to get compressed buffer from memory stream without allocation additional memory (method ToArray returns necessary bytes array but it creates new byte array and then copies all bytes from buffer into the new array). As far as I understand I can only use GetBuffer() which returns entire buffer so in this case I have yet another question: Is it true that all zero bytes in the end of the buffer doesn't belong to the compressed data? In other words can I use GetBuffer with assume that the compressed buffer ends with last non-zero byte?

Also in many cases I can use Length of MemoryStream before closing GZip stream and just add 10 to it after GZip stream is closed is it true for all cases?

Laodicean answered 2/1, 2016 at 13:46 Comment(2)
"and just add 10" is playing with fire.Bindman
I agree, it was just to be sure, thanks!Laodicean
B
3

The constructor of GZipStream has an overload with a leaveOpen parameter.

So when you need to access the MemoryStream after the GZip has Closed (and implicitly, Flushed), pass true to that.

using (var ms = new MemoryStream())
{
    using (var gz = new GZipStream(ms, CompressionMode.Compress, leaveOpen: true))
    {
       // ... write to gz
    }
    Console.WriteLine(ms.Length);  // this is the final and accurate length
}

This still leaves the GetArray() vs getBuiffer() problem but now you can use the buffer with an accurate length.

Bindman answered 2/1, 2016 at 14:15 Comment(1)
Thanks! It is exactly I need at the moment. I knew about this overload but didn't figure out that it could help.Laodicean

© 2022 - 2024 — McMap. All rights reserved.