-4

why can't I get this code here to work? I want to call this on a byte array that was previously compressed....anyway, it just returns an empty string...

    public static string FromGZipToString( this byte[] source )
    {
        using( MemoryStream stream = new MemoryStream( ) )
        {
            stream.Write( source, 0, source.Length );

            using (var gzipstream = new GZipStream(stream, CompressionMode.Decompress))
            using (var reader = new StreamReader(gzipstream)) 
            {
               return reader.ReadToEnd( );
            }
        }
    }

here is the compress code by the way....

    public static byte[] ToGZip( this string source )
    {
        using( var stream = new MemoryStream( ) )
        using( var compressor = new GZipStream( stream, CompressionMode.Compress ) )
        {
            var bytes = System.Text.UTF8Encoding.UTF8.GetBytes( source );

            compressor.Write( bytes, 0, bytes.Length );

            return stream.ToArray( );
        }
    }
Krease
  • 15,805
  • 8
  • 54
  • 86
Timmerz
  • 6,090
  • 5
  • 36
  • 49
  • 6
    did you forget to reset the position of the MemoryStream? – BrokenGlass Oct 22 '10 at 23:45
  • resetting the position after the write does not fix it =( – Timmerz Oct 22 '10 at 23:49
  • updated the code in the post to working copy...I reset the position via seek in the decompression plus closed zip stream before toarray in the compression. – Timmerz Oct 23 '10 at 00:30
  • Replacing the original question with updated code that works with no problems doesn't help anyone else seeing the question. If you think it's useful, post your updated code as an answer (with an explanation) – Krease Jan 04 '16 at 22:17

1 Answers1

5

Your compression routine is faulty. It shouldn't be reading from stream until the compressor has been closed (or disposed), allowing the compressor to finish writing all bytes to the steam.

Check out my answer to this question: compressing and decompressing source data gives result different than source data

Community
  • 1
  • 1
Will
  • 2,512
  • 14
  • 19
  • it seems to be a combination of that with adding stream.Seek(0, SeekOrigin.Begin); after the write in the decompression – Timmerz Oct 23 '10 at 00:15
  • Probably better answered by saying: you need to Flush your compressor before reading the MemoryStream. – spender Oct 23 '10 at 00:17
  • @spender - normally I'd agree with you, but in this case it would mean assuming that Gzip could safely write out remaining bytes without knowing if the end of the stream had been reached (flush doesn't mean eof). We could have used Close instead, but since Dispose does that for us and do the clean up we need ... – Will Oct 23 '10 at 00:31