IO.Compression.DeflateStream compression

Compression.DeflateStream using compression.
when i compress a file to an already open stream that needs to stay open for further writing, my deflatestream doesnt seems to end correctly.
i need to close it to have the full compressed stream.
so as a workaround I ended writing an intermediate file so that i can close the deflatestream and then copyback the compressed stream to my main filestream.
is there a bug or something i did wrong


            byte[] rBuffer = new byte[(int)fread.Length];
            FileStream fout = new FileStream( tmpname, FileMode.Create );
            DeflateStream zip = new DeflateStream( fout, CompressionMode.Compress );
            zip.Write( rBuffer, 0, rBuffer.Length );
            //needs to close here
           zip.Close();


 



Answer this question

IO.Compression.DeflateStream compression

  • John Gordon - MSFT

    think you need to do a zip.flush before you close it

  • Aengus

    i did
    byte[] rBuffer = new byte[(int)fread.Length];

  • Laptiev Igor

    The length you write out should be the same as what you read it.

    Your code:
    zip.Write( rBuffer, 0, rBuffer.Length );

    Tyr:
    zip.Write( rBuffer, 0, fread.Length);

  • cipri

    I tried it too but doesnt change anything.
    i forgot to include the read to buffer in my sample but that is not the problem Big Smile
    dunno if it helps but the difference between ,when i close or not, is 2 byte longer when i close it.

  • José Nelson

    This same bug just burned me too. You must call Close() when you are done compressing. It writes two finalization bytes and one zero byte onto the end. Flush() is not good enough.


  • manhatma

    Aye, it writes those last couple bytes when it's Dispose()'d (which is called durring Close()).

    On the bright side of things, pass a third argument to your DeflateStream constructor -- false.  It's the flag that tells it to leave the passed-in stream open when DeflateStream.Dispose() is done.

  • Surajkb

     not sure then, I've only just started on streams myself Big Smile

    try having a look at http://msdn.microsoft.com/msdnmag/issues/05/11/BasicInstincts/default.aspx 

  • Yogesh Roy MSFT

    you should include a notice in the documentation Big Smile

  • StevenSw

    Only when you close the footer bytes can be written to complete the compression format. We have workitem to revisit and make this better for future version but for now this is the right way to do this.
  • IO.Compression.DeflateStream compression