ExtractionMethods.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #if !NO_FILE
  2. using System;
  3. using System.IO;
  4. #endif
  5. namespace SharpCompress.Common
  6. {
  7. internal static class ExtractionMethods
  8. {
  9. #if !NO_FILE
  10. /// <summary>
  11. /// Extract to specific directory, retaining filename
  12. /// </summary>
  13. public static void WriteEntryToDirectory(IEntry entry, string destinationDirectory,
  14. ExtractionOptions options, Action<string, ExtractionOptions> write)
  15. {
  16. string destinationFileName;
  17. string file = Path.GetFileName(entry.Key);
  18. string fullDestinationDirectoryPath = Path.GetFullPath(destinationDirectory);
  19. options = options ?? new ExtractionOptions()
  20. {
  21. Overwrite = true
  22. };
  23. if (options.ExtractFullPath)
  24. {
  25. string folder = Path.GetDirectoryName(entry.Key);
  26. string destdir = Path.GetFullPath(
  27. Path.Combine(fullDestinationDirectoryPath, folder)
  28. );
  29. if (!Directory.Exists(destdir))
  30. {
  31. if (!destdir.StartsWith(fullDestinationDirectoryPath))
  32. {
  33. throw new ExtractionException("Entry is trying to create a directory outside of the destination directory.");
  34. }
  35. Directory.CreateDirectory(destdir);
  36. }
  37. destinationFileName = Path.Combine(destdir, file);
  38. }
  39. else
  40. {
  41. destinationFileName = Path.Combine(fullDestinationDirectoryPath, file);
  42. }
  43. if (!entry.IsDirectory)
  44. {
  45. destinationFileName = Path.GetFullPath(destinationFileName);
  46. if (!destinationFileName.StartsWith(fullDestinationDirectoryPath))
  47. {
  48. throw new ExtractionException("Entry is trying to write a file outside of the destination directory.");
  49. }
  50. write(destinationFileName, options);
  51. }
  52. else if (options.ExtractFullPath && !Directory.Exists(destinationFileName))
  53. {
  54. Directory.CreateDirectory(destinationFileName);
  55. }
  56. }
  57. public static void WriteEntryToFile(IEntry entry, string destinationFileName,
  58. ExtractionOptions options,
  59. Action<string, FileMode> openAndWrite)
  60. {
  61. FileMode fm = FileMode.Create;
  62. options = options ?? new ExtractionOptions()
  63. {
  64. Overwrite = true
  65. };
  66. if (!options.Overwrite)
  67. {
  68. fm = FileMode.CreateNew;
  69. }
  70. openAndWrite(destinationFileName, fm);
  71. entry.PreserveExtractionOptions(destinationFileName, options);
  72. }
  73. #endif
  74. }
  75. }