IArchiveEntryExtensions.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.IO;
  2. using SharpCompress.Common;
  3. using SharpCompress.IO;
  4. namespace SharpCompress.Archives
  5. {
  6. public static class IArchiveEntryExtensions
  7. {
  8. public static void WriteTo(this IArchiveEntry archiveEntry, Stream streamToWriteTo)
  9. {
  10. if (archiveEntry.Archive.Type == ArchiveType.Rar && archiveEntry.Archive.IsSolid)
  11. {
  12. throw new InvalidFormatException("Cannot use Archive random access on SOLID Rar files.");
  13. }
  14. if (archiveEntry.IsDirectory)
  15. {
  16. throw new ExtractionException("Entry is a file directory and cannot be extracted.");
  17. }
  18. var streamListener = archiveEntry.Archive as IArchiveExtractionListener;
  19. streamListener.EnsureEntriesLoaded();
  20. streamListener.FireEntryExtractionBegin(archiveEntry);
  21. streamListener.FireFilePartExtractionBegin(archiveEntry.Key, archiveEntry.Size, archiveEntry.CompressedSize);
  22. var entryStream = archiveEntry.OpenEntryStream();
  23. if (entryStream == null)
  24. {
  25. return;
  26. }
  27. using (entryStream)
  28. {
  29. using (Stream s = new ListeningStream(streamListener, entryStream))
  30. {
  31. s.TransferTo(streamToWriteTo);
  32. }
  33. }
  34. streamListener.FireEntryExtractionEnd(archiveEntry);
  35. }
  36. #if !NO_FILE
  37. /// <summary>
  38. /// Extract to specific directory, retaining filename
  39. /// </summary>
  40. public static void WriteToDirectory(this IArchiveEntry entry, string destinationDirectory,
  41. ExtractionOptions options = null)
  42. {
  43. ExtractionMethods.WriteEntryToDirectory(entry, destinationDirectory, options,
  44. entry.WriteToFile);
  45. }
  46. /// <summary>
  47. /// Extract to specific file
  48. /// </summary>
  49. public static void WriteToFile(this IArchiveEntry entry, string destinationFileName,
  50. ExtractionOptions options = null)
  51. {
  52. ExtractionMethods.WriteEntryToFile(entry, destinationFileName, options,
  53. (x, fm) =>
  54. {
  55. using (FileStream fs = File.Open(destinationFileName, fm))
  56. {
  57. entry.WriteTo(fs);
  58. }
  59. });
  60. }
  61. #endif
  62. }
  63. }