Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...