using System; using System.IO; namespace ICSharpCode.SharpZipLib.GZip { using static Zip.Compression.Deflater; /// /// An example class to demonstrate compression and decompression of GZip streams. /// public static class GZip { /// /// Decompress the input writing /// uncompressed data to the output stream /// /// The readable stream containing data to decompress. /// The output stream to receive the decompressed data. /// Both streams are closed on completion if true. /// Input or output stream is null public static void Decompress(Stream inStream, Stream outStream, bool isStreamOwner) { if (inStream == null) throw new ArgumentNullException(nameof(inStream), "Input stream is null"); if (outStream == null) throw new ArgumentNullException(nameof(outStream), "Output stream is null"); try { using (GZipInputStream gzipInput = new GZipInputStream(inStream)) { gzipInput.IsStreamOwner = isStreamOwner; Core.StreamUtils.Copy(gzipInput, outStream, new byte[4096]); } } finally { if (isStreamOwner) { // inStream is closed by the GZipInputStream if stream owner outStream.Dispose(); } } } /// /// Compress the input stream sending /// result data to output stream /// /// The readable stream to compress. /// The output stream to receive the compressed data. /// Both streams are closed on completion if true. /// Deflate buffer size, minimum 512 /// Deflate compression level, 0-9 /// Input or output stream is null /// Buffer Size is smaller than 512 /// Compression level outside 0-9 public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, int bufferSize = 512, int level = 6) { if (inStream == null) throw new ArgumentNullException(nameof(inStream), "Input stream is null"); if (outStream == null) throw new ArgumentNullException(nameof(outStream), "Output stream is null"); if (bufferSize < 512) throw new ArgumentOutOfRangeException(nameof(bufferSize), "Deflate buffer size must be >= 512"); if (level < NO_COMPRESSION || level > BEST_COMPRESSION) throw new ArgumentOutOfRangeException(nameof(level), "Compression level must be 0-9"); try { using (GZipOutputStream gzipOutput = new GZipOutputStream(outStream, bufferSize)) { gzipOutput.SetLevel(level); gzipOutput.IsStreamOwner = isStreamOwner; Core.StreamUtils.Copy(inStream, gzipOutput, new byte[bufferSize]); } } finally { if (isStreamOwner) { // outStream is closed by the GZipOutputStream if stream owner inStream.Dispose(); } } } } }