Peter
Peter

Reputation: 11890

DeflateStream closes the input stream

Here is my C# method to write zlib-compressed data and some extra data to a stream:

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

When compressor.Close() is called, it automatically closes the input stream. As a result, I cannot write extra data to the stream.

If I close the compressor after writing my extra data, the order of data is no longer valid. My extra data gets written before the compressed data and not after as I intended to.

Why does DeflateStream.Close() close the input stream as well? Is there a way of getting around it short of writing a stream class that wraps the actual stream class and prevents the latter from closing? Regards.

Upvotes: 1

Views: 521

Answers (1)

DmitryG
DmitryG

Reputation: 17850

The DeflateStream close the underlying stream when closing/disposing because it designed this way:

[__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);
            }
        }
    }
}

By default, DeflateStream owns the underlying stream, so closing the stream also closes the underlying stream.

You can control this behavior by using the specific constructor for the DeflateStream that allow you to leave the underlying stream open:

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

Upvotes: 2

Related Questions