views:

66

answers:

1

final working code is here....

    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( );
        }
    }

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

            stream.Seek(0, SeekOrigin.Begin);

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

seekorigin code can be found here:

http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/6d207e3d-ee4b-4780-80dd-bf1a278a57cd

+4  A: 

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: http://stackoverflow.com/questions/3848021/compressing-and-decompressing-source-data-gives-result-different-than-source-data/3848034#3848034

Will
it seems to be a combination of that with adding stream.Seek(0, SeekOrigin.Begin); after the write in the decompression
Timmerz
Probably better answered by saying: you need to Flush your compressor before reading the MemoryStream.
spender
no, flush does not work...
Timmerz
@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