Compress and UnCompress Stream Extension

// December 6th, 2009 // Useful Code

        /// <summary>
        /// READS FROM SOURCE STREAM AND WRITES COMPRESSED VERSION TO THE DEST STREAM
        /// </summary>
        /// <param name="src">SOURCE STREAM TO COMPRESS</param>
        /// <param name="dest">DEST OF COMPRESSED STREAM</param>
        public static void Compress(this Stream src, Stream dest)
        {
            //CREATE A COMPRESSING GZIP STREAM
            using(GZipStream tmpCompressor = new GZipStream(dest, CompressionMode.Compress))
            {
                int count;
                byte[] buffer = new byte[1024];

                //WHILE WE ARE STILL ABLE TO READ BYTES FROM THE SOURCE WRITE THEM TO THE DEST
                while ((count = src.Read(buffer, 0, buffer.Length)) != 0)
                {
                    tmpCompressor.Write(buffer, 0, count);
                }

                //FLUSH THE STREAM SO ALL DATA IS MOVED INTO THE STREAM
                tmpCompressor.Flush();
            }
        }

        /// <summary>
        /// READS COMPRESSED SOURCE STREAM AND WRITES UNCOMPRESSED VERSION TO THE DEST STREAM
        /// </summary>
        /// <param name="src">SOURCE OF COMPRESSED STREAM</param>
        /// <param name="dest">DEST OF UNCOMPRESSED STREAM</param>
        public static void Uncompress(this Stream src, Stream dest)
        {
            //CREATE A DECOMPRESSING GZIP STREAM
            using (GZipStream tmpDecompressor = new GZipStream(src, CompressionMode.Decompress))
            {
                int count;
                byte[] buffer = new byte[1024];

                //WHILE WE ARE STILL ABLE TO READ BYTES FROM THE SOURCE WRITE THEM TO THE DEST
                while ((count = tmpDecompressor.Read(buffer, 0, buffer.Length)) != 0)
                {
                    dest.Write(buffer, 0, count);
                }

                //FLUSH THE STREAM SO ALL DATA IS MOVED INTO THE STREAM
                dest.Flush();
            }
        }
Be Sociable, Share!
  • RSS
  • Twitter
  • Facebook
  • LinkedIn
  • DeviantArt