GZip.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.IO;
  3. namespace ICSharpCode.SharpZipLib.GZip
  4. {
  5. /// <summary>
  6. /// An example class to demonstrate compression and decompression of GZip streams.
  7. /// </summary>
  8. public static class GZip
  9. {
  10. /// <summary>
  11. /// Decompress the <paramref name="inStream">input</paramref> writing
  12. /// uncompressed data to the <paramref name="outStream">output stream</paramref>
  13. /// </summary>
  14. /// <param name="inStream">The readable stream containing data to decompress.</param>
  15. /// <param name="outStream">The output stream to receive the decompressed data.</param>
  16. /// <param name="isStreamOwner">Both streams are closed on completion if true.</param>
  17. public static void Decompress(Stream inStream, Stream outStream, bool isStreamOwner)
  18. {
  19. if (inStream == null || outStream == null) {
  20. throw new Exception("Null Stream");
  21. }
  22. try {
  23. using (GZipInputStream bzipInput = new GZipInputStream(inStream)) {
  24. bzipInput.IsStreamOwner = isStreamOwner;
  25. Core.StreamUtils.Copy(bzipInput, outStream, new byte[4096]);
  26. }
  27. } finally {
  28. if (isStreamOwner) {
  29. // inStream is closed by the GZipInputStream if stream owner
  30. outStream.Dispose();
  31. }
  32. }
  33. }
  34. /// <summary>
  35. /// Compress the <paramref name="inStream">input stream</paramref> sending
  36. /// result data to <paramref name="outStream">output stream</paramref>
  37. /// </summary>
  38. /// <param name="inStream">The readable stream to compress.</param>
  39. /// <param name="outStream">The output stream to receive the compressed data.</param>
  40. /// <param name="isStreamOwner">Both streams are closed on completion if true.</param>
  41. /// <param name="level">Block size acts as compression level (1 to 9) with 1 giving
  42. /// the lowest compression and 9 the highest.</param>
  43. public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, int level)
  44. {
  45. if (inStream == null || outStream == null) {
  46. throw new Exception("Null Stream");
  47. }
  48. try {
  49. using (GZipOutputStream bzipOutput = new GZipOutputStream(outStream, level)) {
  50. bzipOutput.IsStreamOwner = isStreamOwner;
  51. Core.StreamUtils.Copy(inStream, bzipOutput, new byte[4096]);
  52. }
  53. } finally {
  54. if (isStreamOwner) {
  55. // outStream is closed by the GZipOutputStream if stream owner
  56. inStream.Dispose();
  57. }
  58. }
  59. }
  60. }
  61. }