GZipWriter.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.IO;
  3. using SharpCompress.Common;
  4. using SharpCompress.Compressors;
  5. using SharpCompress.Compressors.Deflate;
  6. using SharpCompress.IO;
  7. namespace SharpCompress.Writers.GZip
  8. {
  9. public class GZipWriter : AbstractWriter
  10. {
  11. private bool _wroteToStream;
  12. public GZipWriter(Stream destination, GZipWriterOptions options = null)
  13. : base(ArchiveType.GZip, options ?? new GZipWriterOptions())
  14. {
  15. if (WriterOptions.LeaveStreamOpen)
  16. {
  17. destination = new NonDisposingStream(destination);
  18. }
  19. InitalizeStream(new GZipStream(destination, CompressionMode.Compress,
  20. options?.CompressionLevel ?? CompressionLevel.Default,
  21. WriterOptions.ArchiveEncoding.GetEncoding()));
  22. }
  23. protected override void Dispose(bool isDisposing)
  24. {
  25. if (isDisposing)
  26. {
  27. //dispose here to finish the GZip, GZip won't close the underlying stream
  28. OutputStream.Dispose();
  29. }
  30. base.Dispose(isDisposing);
  31. }
  32. public override void Write(string filename, Stream source, DateTime? modificationTime)
  33. {
  34. if (_wroteToStream)
  35. {
  36. throw new ArgumentException("Can only write a single stream to a GZip file.");
  37. }
  38. GZipStream stream = OutputStream as GZipStream;
  39. stream.FileName = filename;
  40. stream.LastModified = modificationTime;
  41. source.TransferTo(stream);
  42. _wroteToStream = true;
  43. }
  44. }
  45. }