是否有可能获得封闭内存流的长度? [英] Is it possible to get length of closed memory stream?

查看:66
本文介绍了是否有可能获得封闭内存流的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将GZipStream与MemoryStream一起使用。我写了我需要的所有字节,然后关闭gzip流,因此之后我需要从内存流中获取压缩缓冲区,而不分配额外的内存(方法ToArray返回必要的字节数组,但它会创建新的字节数组,然后将缓冲区中的所有字节复制到新的字节数组中数组)。
据我了解,我只能使用GetBuffer()来返回整个缓冲区,因此在这种情况下,我还有另一个问题:
是真的,缓冲区末尾的所有零字节都没有属于压缩数据?换句话说,我可以在假设压缩缓冲区以最后一个非零字节结尾的情况下使用GetBuffer吗?

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?

在很多情况下,我可以在关闭GZip流之前使用Length的MemoryStream并在关闭GZip流后向其添加10,是否在所有情况下都是这样?

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?

推荐答案

<$ c $的构造函数c> GZipStream 有一个带有 leaveOpen 参数的重载。

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

因此,当您需要在GZip关闭(隐式地刷新)后访问MemoryStream时,请传递 true 对此。

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
}

这仍然保留了GetArray() vs getBuiffer()问题,但现在您可以使用长度正确的缓冲区了。

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

这篇关于是否有可能获得封闭内存流的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆