BZip2.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.IO;
  3. namespace ICSharpCode.SharpZipLib.BZip2
  4. {
  5. /// <summary>
  6. /// An example class to demonstrate compression and decompression of BZip2 streams.
  7. /// </summary>
  8. public static class BZip2
  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)
  20. throw new ArgumentNullException(nameof(inStream));
  21. if (outStream == null)
  22. throw new ArgumentNullException(nameof(outStream));
  23. try
  24. {
  25. using (BZip2InputStream bzipInput = new BZip2InputStream(inStream))
  26. {
  27. bzipInput.IsStreamOwner = isStreamOwner;
  28. Core.StreamUtils.Copy(bzipInput, outStream, new byte[4096]);
  29. }
  30. }
  31. finally
  32. {
  33. if (isStreamOwner)
  34. {
  35. // inStream is closed by the BZip2InputStream if stream owner
  36. outStream.Dispose();
  37. }
  38. }
  39. }
  40. /// <summary>
  41. /// Compress the <paramref name="inStream">input stream</paramref> sending
  42. /// result data to <paramref name="outStream">output stream</paramref>
  43. /// </summary>
  44. /// <param name="inStream">The readable stream to compress.</param>
  45. /// <param name="outStream">The output stream to receive the compressed data.</param>
  46. /// <param name="isStreamOwner">Both streams are closed on completion if true.</param>
  47. /// <param name="level">Block size acts as compression level (1 to 9) with 1 giving
  48. /// the lowest compression and 9 the highest.</param>
  49. public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, int level)
  50. {
  51. if (inStream == null)
  52. throw new ArgumentNullException(nameof(inStream));
  53. if (outStream == null)
  54. throw new ArgumentNullException(nameof(outStream));
  55. try
  56. {
  57. using (BZip2OutputStream bzipOutput = new BZip2OutputStream(outStream, level))
  58. {
  59. bzipOutput.IsStreamOwner = isStreamOwner;
  60. Core.StreamUtils.Copy(inStream, bzipOutput, new byte[4096]);
  61. }
  62. }
  63. finally
  64. {
  65. if (isStreamOwner)
  66. {
  67. // outStream is closed by the BZip2OutputStream if stream owner
  68. inStream.Dispose();
  69. }
  70. }
  71. }
  72. }
  73. }