Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

c# - Is it possible to get length of closed memory stream?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...