2
votes

I was trying to compress a byte array using DeflateStream. After wring the data, I was looking for a way to close the compression (mark as done). At first, I tried Dispose() then Close(), but those made the result MemoryStream unreadable. Then I thought I may need to Flush(), but the description said "The current implementation of this method has no functionality"

enter image description here

But it seems that without Flush(), the result seems empty. What does it mean that "The current implementation of this method has no functionality"?

    static void Main(string[] args)
    {
        byte[] result = Encoding.UTF8.GetBytes("わたしのこいはみなみのかぜにのってはしるわ");
        var output = new MemoryStream();
        var dstream = new DeflateStream(output, CompressionLevel.Optimal);
        dstream.Write(result, 0, result.Length);
        var compressedSize1 = output.Position;
        dstream.Flush();
        var compressedSize2 = output.Position;

enter image description here

1
haha nice username!BCLC

1 Answers

2
votes

What does it mean that "The current implementation of this method has no functionality" ?

it means: it doesn't do anything, so calling Flush() by itself isn't going to help. You need to close the deflate stream for it to finish writing what it needs, but without closing the underlying stream (blocks will be written as you write to the stream, as the internal buffer fills - but the final partial block cannot be written until the data is ready to be terminated; not all compression sequences support being able to flush at an arbitrary point and then resume compressed data in additional blocks)

What you probably want is:

using (var dstream = new DeflateStream(output, CompressionLevel.Optimal, true))
{
  // Your deflate code
}
// Now check the memory stream

Note the extra bool leaveOpen parameter usage.