Wednesday, January 25, 2012

Manual GZipStream Compression / Decompression

 public MemoryStream GZipCompress(MemoryStream mStreamOrg)
         {
             try
             {

                 byte[] buffer = mStreamOrg.ToArray();

                 MemoryStream ms = new MemoryStream();
                 // Use the newly created memory stream for the compressed data.
                 GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
                 Console.WriteLine("Compression");
                 compressedzipStream.Write(buffer, 0, buffer.Length);
                 // Close the stream.
                 compressedzipStream.Close();
                 Console.WriteLine("Original size: {0}, Compressed size: {1}", buffer.Length, ms.Length);

                 // Reset the memory stream position to begin decompression.
                 ms.Position = 0;
                 return ms;

             } // end try
             catch
             {
                 return null;
             }
            
         }

         private  void GZipDeCompress(MemoryStream compressedMemoryStream, long actualLength)
         {
            
             GZipStream zipStream = new GZipStream(compressedMemoryStream, CompressionMode.Decompress);
             Console.WriteLine("Decompression");
             byte[] decompressedBuffer = new byte[actualLength];
             // Use the ReadAllBytesFromStream to read the stream.
             int totalCount = ReadAllBytesFromStream(zipStream, decompressedBuffer);
             Console.WriteLine("Decompressed {0} bytes", totalCount);

            string result = Encoding.UTF8.GetString(decompressedBuffer);
             MemoryStream msTemp = new MemoryStream(Encoding.UTF8.GetBytes(result));

             var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(EntityObj));


             EntityObj deserializedObj =
                 (EntityObj)serializer.ReadObject(msTemp);



             zipStream.Close();
         }

 public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
         {
             // Use this method is used to read all bytes from a stream.
             int offset = 0;
             int totalCount = 0;
             //while (true)
             //{
             //    int bytesRead = stream.Read(buffer, offset, 100);
             //    if (bytesRead == 0)
             //    {
             //        break;
             //    }
             //    offset += bytesRead;
             //    totalCount += bytesRead;
             //}
             totalCount = stream.Read(buffer, offset, buffer.Length);
             return totalCount;
         }

No comments:

Post a Comment