C # file stream compression decompression

Source: Internet
Author: User
Tags deflater
/// <summary>
    /// File stream compression and decompression
    /// </ summary>
    public class ZipHelper
    {
        public static int BEST_COMPRESSION = 9;
        public static int BEST_SPEED = 1;
        public static int DEFAULT_COMPRESSION = -1;
        public static int NO_COMPRESSION = 0;

        #region DeflateCompression

        #region DeflateCompression
        /// <summary>
        /// Deflate compression (the default compression level is the highest)
        /// </ summary>
        /// <param name = "stream"> </ param>
        /// <returns> </ returns>
        public static Stream Deflate (Stream stream)
        {
            return ZipHelper.Deflate (stream, ZipHelper.DEFAULT_COMPRESSION);
        }
        /// <summary>
        /// Deflate compression
        /// </ summary>
        /// <param name = "stream"> </ param>
        /// <param name = "level"> Compression quality level (0 ~ 9) </ param>
        /// <returns> </ returns>
        public static Stream Deflate (Stream stream, int level)
        {
            byte [] array = ZipHelper.StreamToBytes (stream);
            byte [] array2 = new byte [array.Length];
            Deflater deflater = new Deflater ();
            deflater.SetLevel (level);
            deflater.SetStrategy (DeflateStrategy.Default);
            deflater.SetInput (array);
            deflater.Finish ();
            int num = deflater.Deflate (array2);
            byte [] array3 = new byte [num];
            Array.Copy (array2, array3, num);
            return ZipHelper.BytesToStream (array3);
        }

        /// <summary>
        /// Deflate compression
        /// </ summary>
        /// <param name = "input"> </ param>
        /// <param name = "level"> Compression quality level (0 ~ 9) </ param>
        /// <returns> </ returns>
        public static byte [] Deflate (byte [] input, int level)
        {
            byte [] result;
            try
            {
                if (input == null && input.Length == 0)
                {
                    result = new byte [0];
                }
                else
                {
                    byte [] array = new byte [input.Length];
                    Deflater deflater = new Deflater ();
                    deflater.SetLevel (level);
                    deflater.SetStrategy (DeflateStrategy.Default);
                    deflater.SetInput (input);
                    deflater.Finish ();
                    int num = deflater.Deflate (array);
                    byte [] array2 = new byte [num];
                    Array.Copy (array, array2, num);
                    result = array2;
                }
            }
            catch (Exception innerException)
            {
                throw new Exception ("An error occurred in the compressor!", innerException);
            }
            return result;
        }
        #endregion

        #region InflateUnzip
        /// <summary>
        /// Inflate decompression
        /// </ summary>
        /// <param name = "input"> </ param>
        /// <returns> </ returns>
        public static byte [] Inflate (byte [] input)
        {
            byte [] result;
            try
            {
                if (input == null && input.Length == 0)
                {
                    result = new byte [0];
                }
                else
                {
                    Inflater inflater = new Inflater ();
                    inflater.SetInput (input);
                    byte [] array = new byte [1024];
                    using (MemoryStream memoryStream = new MemoryStream ())
                    {
                        for (int i = inflater.Inflate (array, 0, array.Length); i> 0; i = inflater.Inflate (array, 0, array.Length))
                        {
                            memoryStream.Write (array, 0, i);
                        }
                        byte [] buffer = memoryStream.GetBuffer ();
                        memoryStream.Close ();
                        result = buffer;
                    }
                }
            }
            catch (Exception innerException)
            {
                throw new Exception ("An uncompressor error occurred!", innerException);
            }
            return result;
        }
        /// <summary>
        /// Inflate decompression
        /// </ summary>
        /// <param name = "zipStream"> </ param>
        /// <returns> </ returns>
        public static Stream Inflate (Stream zipStream)
        {
            byte [] input = ZipHelper.StreamToBytes (zipStream);
            byte [] bytes = ZipHelper.Inflate (input);
            return ZipHelper.BytesToStream (bytes);
        }
        #endregion

        #endregion

        #region GZip compression
        /// <summary>
        /// GZip compression
        /// </ summary>
        /// <param name = "srcStream"> </ param>
        /// <param name = "output"> </ param>
        public static void GZipCompress (Stream srcStream, Stream output)
        {
            ZipHelper.GZipCompress (srcStream, 6, output);
        }
        /// <summary>
        /// GZip compression
        /// </ summary>
        /// <param name = "srcStream"> </ param>
        /// <param name = "compressLevel"> Compression quality level (0 ~ 9) </ param>
        /// <param name = "output"> </ param>
        public static void GZipCompress (Stream srcStream, int compressLevel, Stream output)
        {
            if (compressLevel <1 || compressLevel> 9)
            {
                throw new Exception (string.Format ("The compression level you specified {0} is not in the valid range (1-9)", compressLevel));
            }
            srcStream.Position = 0L;
            GZipOutputStream gZipOutputStream = new GZipOutputStream (output);
            gZipOutputStream.SetLevel (compressLevel);
            try
            {
                int i = 4096;
                byte [] buffer = new byte [i];
                while (i> 0)
                {
                    i = srcStream.Read (buffer, 0, i);
                    gZipOutputStream.Write (buffer, 0, i);
                }
            }
            catch (Exception ex)
            {
                throw new Exception ("GZip compression error:" + ex.Message);
            }
            srcStream.Close ();
            gZipOutputStream.Finish ();
        }
        /// <summary>
        /// GZip decompression
        /// </ summary>
        /// <param name = "zipStream"> </ param>
        /// <param name = "outputStream"> </ param>
        public static void GZipDeCompress (Stream zipStream, Stream outputStream)
        {
            GZipInputStream gZipInputStream = new GZipInputStream (zipStream);
            try
            {
                int i = 4096;
                byte [] buffer = new byte [i];
                while (i> 0)
                {
                    i = gZipInputStream.Read (buffer, 0, i);
                    outputStream.Write (buffer, 0, i);
                }
            }
            catch (Exception ex)
            {
                throw new Exception ("GZip decompression error:" + ex.Message);
            }
            zipStream.Close ();
            gZipInputStream.Close ();
        }
        #endregion

        #region BZip2 Compression
        /// <summary>
        /// BZip2 compression
        /// </ summary>
        /// <param name = "inStream"> </ param>
        /// <param name = "outStream"> </ param>
        /// <param name = "blockSize"> </ param>
        public static void BZip2Compress (Stream inStream, Stream outStream, int blockSize)
        {
            BZip2.Compress (inStream, outStream, blockSize);
        }
        /// <summary>
        /// BZip2 decompression
        /// </ summary>
        /// <param name = "inStream"> </ param>
        /// <param name = "outStream"> </ param>
        public static void BZip2Decompress (Stream inStream, Stream outStream)
        {
            BZip2.Decompress (inStream, outStream);
        }
        #endregion


        private static byte [] StreamToBytes (Stream stream)
        {
            byte [] array = new byte [stream.Length];
            stream.Seek (0L, SeekOrigin.Begin);
            stream.Read (array, 0, array.Length);
            stream.Close ();
            return array;
        }
        private static Stream BytesToStream (byte [] bytes)
        {
            return new MemoryStream (bytes);
        }
        private static void StreamToFile (Stream stream, string fileName)
        {
            byte [] array = new byte [stream.Length];
            stream.Read (array, 0, array.Length);
            stream.Seek (0L, SeekOrigin.Begin);
            FileStream fileStream = new FileStream (fileName, FileMode.Create);
            BinaryWriter binaryWriter = new BinaryWriter (fileStream);
            binaryWriter.Write (array);
            binaryWriter.Close ();
            fileStream.Close ();
        }
        private static Stream FileToStream (string fileName)
        {
            FileStream fileStream = new FileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte [] array = new byte [fileStream.Length];
            fileStream.Read (array, 0, array.Length);
            fileStream.Close ();
            return new MemoryStream (array);
        }
    }  

The above is the C # file stream compression decompression content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.