BZip2Stream.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System.IO;
  2. namespace SharpCompress.Compressors.BZip2
  3. {
  4. public class BZip2Stream : Stream
  5. {
  6. private readonly Stream stream;
  7. private bool isDisposed;
  8. /// <summary>
  9. /// Create a BZip2Stream
  10. /// </summary>
  11. /// <param name="stream">The stream to read from</param>
  12. /// <param name="compressionMode">Compression Mode</param>
  13. /// <param name="decompressConcatenated">Decompress Concatenated</param>
  14. public BZip2Stream(Stream stream, CompressionMode compressionMode,
  15. bool decompressConcatenated)
  16. {
  17. Mode = compressionMode;
  18. if (Mode == CompressionMode.Compress)
  19. {
  20. this.stream = new CBZip2OutputStream(stream);
  21. }
  22. else
  23. {
  24. this.stream = new CBZip2InputStream(stream, decompressConcatenated);
  25. }
  26. }
  27. public void Finish()
  28. {
  29. (stream as CBZip2OutputStream)?.Finish();
  30. }
  31. protected override void Dispose(bool disposing)
  32. {
  33. if (isDisposed)
  34. {
  35. return;
  36. }
  37. isDisposed = true;
  38. if (disposing)
  39. {
  40. stream.Dispose();
  41. }
  42. }
  43. public CompressionMode Mode { get; }
  44. public override bool CanRead => stream.CanRead;
  45. public override bool CanSeek => stream.CanSeek;
  46. public override bool CanWrite => stream.CanWrite;
  47. public override void Flush()
  48. {
  49. stream.Flush();
  50. }
  51. public override long Length => stream.Length;
  52. public override long Position { get => stream.Position; set => stream.Position = value; }
  53. public override int Read(byte[] buffer, int offset, int count)
  54. {
  55. return stream.Read(buffer, offset, count);
  56. }
  57. public override int ReadByte()
  58. {
  59. return stream.ReadByte();
  60. }
  61. public override long Seek(long offset, SeekOrigin origin)
  62. {
  63. return stream.Seek(offset, origin);
  64. }
  65. public override void SetLength(long value)
  66. {
  67. stream.SetLength(value);
  68. }
  69. public override void Write(byte[] buffer, int offset, int count)
  70. {
  71. stream.Write(buffer, offset, count);
  72. }
  73. public override void WriteByte(byte value)
  74. {
  75. stream.WriteByte(value);
  76. }
  77. /// <summary>
  78. /// Consumes two bytes to test if there is a BZip2 header
  79. /// </summary>
  80. /// <param name="stream"></param>
  81. /// <returns></returns>
  82. public static bool IsBZip2(Stream stream)
  83. {
  84. BinaryReader br = new BinaryReader(stream);
  85. byte[] chars = br.ReadBytes(2);
  86. if (chars.Length < 2 || chars[0] != 'B' || chars[1] != 'Z')
  87. {
  88. return false;
  89. }
  90. return true;
  91. }
  92. }
  93. }