DeflateStream关闭输入流

时间:2016-06-17 07:23:39

标签: c# .net

这是我的C#方法,用于将zlib压缩数据和一些额外数据写入流:

  using (var compressor = new DeflateStream(compressStream, CompressionMode.Compress)) {
    compressor.Write(input, 0, input.Length);
    compressor.Close();
    compessStream.Write(extraData, 0, extraData.Length);
  }

调用compressor.Close()时,它会自动关闭输入流。因此,我无法将额外数据写入流中。

如果在写完额外数据后关闭压缩器,则数据顺序不再有效。我的额外数据在压缩数据之前写入,而不是按照我的意图写入。

为什么DeflateStream.Close()也会关闭输入流?有没有办法绕过它编写一个包含实际流类并防止后者关闭的流类?问候。

1 个答案:

答案 0 :(得分:0)

DeflateStream在关闭/处理时关闭底层流,因为它采用这种方式设计:

[__DynamicallyInvokable]
protected override void Dispose(bool disposing)
{
    try {
        this.PurgeBuffers(disposing);
    }
    finally {
        try {
            if (disposing && !this._leaveOpen && this._stream != null) {
                this._stream.Close();
            }
        }
        finally {
            this._stream = null;
            try {
                if (this.deflater != null)  {
                    this.deflater.Dispose();
                }
            }
            finally {
                this.deflater = null;
                base.Dispose(disposing);
            }
        }
    }
}

默认情况下,DeflateStream拥有基础流,因此关闭流也会关闭基础流。

您可以使用允许您打开基础流的DeflateStream的specific constructor来控制此行为:

public DeflateStream(
    Stream stream,
    CompressionMode mode,
    bool leaveOpen
)