BZip2.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.IO;
  3. namespace System.Net.ApiService.Compression.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 || outStream == null)
  20. {
  21. throw new Exception("Null Stream");
  22. }
  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 || outStream == null)
  52. {
  53. throw new Exception("Null Stream");
  54. }
  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. }