FastZip.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. using System.Net.ApiService.Compression.Core;
  2. using System.Net.ApiService.Compression.Zip.Compression;
  3. using System;
  4. using System.IO;
  5. using static System.Net.ApiService.Compression.Zip.Compression.Deflater;
  6. namespace System.Net.ApiService.Compression.Zip {
  7. /// <summary>
  8. /// FastZipEvents supports all events applicable to <see cref="FastZip">FastZip</see> operations.
  9. /// </summary>
  10. public class FastZipEvents
  11. {
  12. /// <summary>
  13. /// Delegate to invoke when processing directories.
  14. /// </summary>
  15. public event EventHandler<DirectoryEventArgs> ProcessDirectory;
  16. /// <summary>
  17. /// Delegate to invoke when processing files.
  18. /// </summary>
  19. public ProcessFileHandler ProcessFile;
  20. /// <summary>
  21. /// Delegate to invoke during processing of files.
  22. /// </summary>
  23. public ProgressHandler Progress;
  24. /// <summary>
  25. /// Delegate to invoke when processing for a file has been completed.
  26. /// </summary>
  27. public CompletedFileHandler CompletedFile;
  28. /// <summary>
  29. /// Delegate to invoke when processing directory failures.
  30. /// </summary>
  31. public DirectoryFailureHandler DirectoryFailure;
  32. /// <summary>
  33. /// Delegate to invoke when processing file failures.
  34. /// </summary>
  35. public FileFailureHandler FileFailure;
  36. /// <summary>
  37. /// Raise the <see cref="DirectoryFailure">directory failure</see> event.
  38. /// </summary>
  39. /// <param name="directory">The directory causing the failure.</param>
  40. /// <param name="e">The exception for this event.</param>
  41. /// <returns>A boolean indicating if execution should continue or not.</returns>
  42. public bool OnDirectoryFailure(string directory, Exception e)
  43. {
  44. bool result = false;
  45. DirectoryFailureHandler handler = DirectoryFailure;
  46. if (handler != null)
  47. {
  48. var args = new ScanFailureEventArgs(directory, e);
  49. handler(this, args);
  50. result = args.ContinueRunning;
  51. }
  52. return result;
  53. }
  54. /// <summary>
  55. /// Fires the <see cref="FileFailure"> file failure handler delegate</see>.
  56. /// </summary>
  57. /// <param name="file">The file causing the failure.</param>
  58. /// <param name="e">The exception for this failure.</param>
  59. /// <returns>A boolean indicating if execution should continue or not.</returns>
  60. public bool OnFileFailure(string file, Exception e)
  61. {
  62. FileFailureHandler handler = FileFailure;
  63. bool result = (handler != null);
  64. if (result)
  65. {
  66. var args = new ScanFailureEventArgs(file, e);
  67. handler(this, args);
  68. result = args.ContinueRunning;
  69. }
  70. return result;
  71. }
  72. /// <summary>
  73. /// Fires the <see cref="ProcessFile">ProcessFile delegate</see>.
  74. /// </summary>
  75. /// <param name="file">The file being processed.</param>
  76. /// <returns>A boolean indicating if execution should continue or not.</returns>
  77. public bool OnProcessFile(string file)
  78. {
  79. bool result = true;
  80. ProcessFileHandler handler = ProcessFile;
  81. if (handler != null)
  82. {
  83. var args = new ScanEventArgs(file);
  84. handler(this, args);
  85. result = args.ContinueRunning;
  86. }
  87. return result;
  88. }
  89. /// <summary>
  90. /// Fires the <see cref="CompletedFile"/> delegate
  91. /// </summary>
  92. /// <param name="file">The file whose processing has been completed.</param>
  93. /// <returns>A boolean indicating if execution should continue or not.</returns>
  94. public bool OnCompletedFile(string file)
  95. {
  96. bool result = true;
  97. CompletedFileHandler handler = CompletedFile;
  98. if (handler != null)
  99. {
  100. var args = new ScanEventArgs(file);
  101. handler(this, args);
  102. result = args.ContinueRunning;
  103. }
  104. return result;
  105. }
  106. /// <summary>
  107. /// Fires the <see cref="ProcessDirectory">process directory</see> delegate.
  108. /// </summary>
  109. /// <param name="directory">The directory being processed.</param>
  110. /// <param name="hasMatchingFiles">Flag indicating if the directory has matching files as determined by the current filter.</param>
  111. /// <returns>A <see cref="bool"/> of true if the operation should continue; false otherwise.</returns>
  112. public bool OnProcessDirectory(string directory, bool hasMatchingFiles)
  113. {
  114. bool result = true;
  115. EventHandler<DirectoryEventArgs> handler = ProcessDirectory;
  116. if (handler != null)
  117. {
  118. var args = new DirectoryEventArgs(directory, hasMatchingFiles);
  119. handler(this, args);
  120. result = args.ContinueRunning;
  121. }
  122. return result;
  123. }
  124. /// <summary>
  125. /// The minimum timespan between <see cref="Progress"/> events.
  126. /// </summary>
  127. /// <value>The minimum period of time between <see cref="Progress"/> events.</value>
  128. /// <seealso cref="Progress"/>
  129. /// <remarks>The default interval is three seconds.</remarks>
  130. public TimeSpan ProgressInterval
  131. {
  132. get { return progressInterval_; }
  133. set { progressInterval_ = value; }
  134. }
  135. #region Instance Fields
  136. private TimeSpan progressInterval_ = TimeSpan.FromSeconds(3);
  137. #endregion Instance Fields
  138. }
  139. /// <summary>
  140. /// FastZip provides facilities for creating and extracting zip files.
  141. /// </summary>
  142. public class FastZip
  143. {
  144. #region Enumerations
  145. /// <summary>
  146. /// Defines the desired handling when overwriting files during extraction.
  147. /// </summary>
  148. public enum Overwrite
  149. {
  150. /// <summary>
  151. /// Prompt the user to confirm overwriting
  152. /// </summary>
  153. Prompt,
  154. /// <summary>
  155. /// Never overwrite files.
  156. /// </summary>
  157. Never,
  158. /// <summary>
  159. /// Always overwrite files.
  160. /// </summary>
  161. Always
  162. }
  163. #endregion Enumerations
  164. #region Constructors
  165. /// <summary>
  166. /// Initialise a default instance of <see cref="FastZip"/>.
  167. /// </summary>
  168. public FastZip()
  169. {
  170. }
  171. /// <summary>
  172. /// Initialise a new instance of <see cref="FastZip"/>
  173. /// </summary>
  174. /// <param name="events">The <see cref="FastZipEvents">events</see> to use during operations.</param>
  175. public FastZip(FastZipEvents events)
  176. {
  177. events_ = events;
  178. }
  179. #endregion Constructors
  180. #region Properties
  181. /// <summary>
  182. /// Get/set a value indicating wether empty directories should be created.
  183. /// </summary>
  184. public bool CreateEmptyDirectories
  185. {
  186. get { return createEmptyDirectories_; }
  187. set { createEmptyDirectories_ = value; }
  188. }
  189. /// <summary>
  190. /// Get / set the password value.
  191. /// </summary>
  192. public string Password
  193. {
  194. get { return password_; }
  195. set { password_ = value; }
  196. }
  197. /// <summary>
  198. /// Get or set the <see cref="INameTransform"></see> active when creating Zip files.
  199. /// </summary>
  200. /// <seealso cref="EntryFactory"></seealso>
  201. public INameTransform NameTransform
  202. {
  203. get { return entryFactory_.NameTransform; }
  204. set
  205. {
  206. entryFactory_.NameTransform = value;
  207. }
  208. }
  209. /// <summary>
  210. /// Get or set the <see cref="IEntryFactory"></see> active when creating Zip files.
  211. /// </summary>
  212. public IEntryFactory EntryFactory
  213. {
  214. get { return entryFactory_; }
  215. set
  216. {
  217. if (value == null)
  218. {
  219. entryFactory_ = new ZipEntryFactory();
  220. }
  221. else
  222. {
  223. entryFactory_ = value;
  224. }
  225. }
  226. }
  227. /// <summary>
  228. /// Gets or sets the setting for <see cref="UseZip64">Zip64 handling when writing.</see>
  229. /// </summary>
  230. /// <remarks>
  231. /// The default value is dynamic which is not backwards compatible with old
  232. /// programs and can cause problems with XP's built in compression which cant
  233. /// read Zip64 archives. However it does avoid the situation were a large file
  234. /// is added and cannot be completed correctly.
  235. /// NOTE: Setting the size for entries before they are added is the best solution!
  236. /// By default the EntryFactory used by FastZip will set fhe file size.
  237. /// </remarks>
  238. public UseZip64 UseZip64
  239. {
  240. get { return useZip64_; }
  241. set { useZip64_ = value; }
  242. }
  243. /// <summary>
  244. /// Get/set a value indicating wether file dates and times should
  245. /// be restored when extracting files from an archive.
  246. /// </summary>
  247. /// <remarks>The default value is false.</remarks>
  248. public bool RestoreDateTimeOnExtract
  249. {
  250. get
  251. {
  252. return restoreDateTimeOnExtract_;
  253. }
  254. set
  255. {
  256. restoreDateTimeOnExtract_ = value;
  257. }
  258. }
  259. /// <summary>
  260. /// Get/set a value indicating whether file attributes should
  261. /// be restored during extract operations
  262. /// </summary>
  263. public bool RestoreAttributesOnExtract
  264. {
  265. get { return restoreAttributesOnExtract_; }
  266. set { restoreAttributesOnExtract_ = value; }
  267. }
  268. /// <summary>
  269. /// Get/set the Compression Level that will be used
  270. /// when creating the zip
  271. /// </summary>
  272. public Deflater.CompressionLevel CompressionLevel
  273. {
  274. get { return compressionLevel_; }
  275. set { compressionLevel_ = value; }
  276. }
  277. #endregion Properties
  278. #region Delegates
  279. /// <summary>
  280. /// Delegate called when confirming overwriting of files.
  281. /// </summary>
  282. public delegate bool ConfirmOverwriteDelegate(string fileName);
  283. #endregion Delegates
  284. #region CreateZip
  285. /// <summary>
  286. /// Create a zip file.
  287. /// </summary>
  288. /// <param name="zipFileName">The name of the zip file to create.</param>
  289. /// <param name="sourceDirectory">The directory to source files from.</param>
  290. /// <param name="recurse">True to recurse directories, false for no recursion.</param>
  291. /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param>
  292. /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param>
  293. public void CreateZip(string zipFileName, string sourceDirectory,
  294. bool recurse, string fileFilter, string directoryFilter)
  295. {
  296. CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, directoryFilter);
  297. }
  298. /// <summary>
  299. /// Create a zip file/archive.
  300. /// </summary>
  301. /// <param name="zipFileName">The name of the zip file to create.</param>
  302. /// <param name="sourceDirectory">The directory to obtain files and directories from.</param>
  303. /// <param name="recurse">True to recurse directories, false for no recursion.</param>
  304. /// <param name="fileFilter">The file filter to apply.</param>
  305. public void CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter)
  306. {
  307. CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, null);
  308. }
  309. /// <summary>
  310. /// Create a zip archive sending output to the <paramref name="outputStream"/> passed.
  311. /// </summary>
  312. /// <param name="outputStream">The stream to write archive data to.</param>
  313. /// <param name="sourceDirectory">The directory to source files from.</param>
  314. /// <param name="recurse">True to recurse directories, false for no recursion.</param>
  315. /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param>
  316. /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param>
  317. /// <remarks>The <paramref name="outputStream"/> is closed after creation.</remarks>
  318. public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter)
  319. {
  320. NameTransform = new ZipNameTransform(sourceDirectory);
  321. sourceDirectory_ = sourceDirectory;
  322. using (outputStream_ = new ZipOutputStream(outputStream))
  323. {
  324. outputStream_.SetLevel((int)CompressionLevel);
  325. if (password_ != null)
  326. {
  327. outputStream_.Password = password_;
  328. }
  329. outputStream_.UseZip64 = UseZip64;
  330. var scanner = new FileSystemScanner(fileFilter, directoryFilter);
  331. scanner.ProcessFile += ProcessFile;
  332. if (this.CreateEmptyDirectories)
  333. {
  334. scanner.ProcessDirectory += ProcessDirectory;
  335. }
  336. if (events_ != null)
  337. {
  338. if (events_.FileFailure != null)
  339. {
  340. scanner.FileFailure += events_.FileFailure;
  341. }
  342. if (events_.DirectoryFailure != null)
  343. {
  344. scanner.DirectoryFailure += events_.DirectoryFailure;
  345. }
  346. }
  347. scanner.Scan(sourceDirectory, recurse);
  348. }
  349. }
  350. #endregion CreateZip
  351. #region ExtractZip
  352. /// <summary>
  353. /// Extract the contents of a zip file.
  354. /// </summary>
  355. /// <param name="zipFileName">The zip file to extract from.</param>
  356. /// <param name="targetDirectory">The directory to save extracted information in.</param>
  357. /// <param name="fileFilter">A filter to apply to files.</param>
  358. public void ExtractZip(string zipFileName, string targetDirectory, string fileFilter)
  359. {
  360. ExtractZip(zipFileName, targetDirectory, Overwrite.Always, null, fileFilter, null, restoreDateTimeOnExtract_);
  361. }
  362. /// <summary>
  363. /// Extract the contents of a zip file.
  364. /// </summary>
  365. /// <param name="zipFileName">The zip file to extract from.</param>
  366. /// <param name="targetDirectory">The directory to save extracted information in.</param>
  367. /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
  368. /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
  369. /// <param name="fileFilter">A filter to apply to files.</param>
  370. /// <param name="directoryFilter">A filter to apply to directories.</param>
  371. /// <param name="restoreDateTime">Flag indicating whether to restore the date and time for extracted files.</param>
  372. /// <param name="allowParentTraversal">Allow parent directory traversal in file paths (e.g. ../file)</param>
  373. public void ExtractZip(string zipFileName, string targetDirectory,
  374. Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate,
  375. string fileFilter, string directoryFilter, bool restoreDateTime, bool allowParentTraversal = false)
  376. {
  377. Stream inputStream = File.Open(zipFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
  378. ExtractZip(inputStream, targetDirectory, overwrite, confirmDelegate, fileFilter, directoryFilter, restoreDateTime, true, allowParentTraversal);
  379. }
  380. /// <summary>
  381. /// Extract the contents of a zip file held in a stream.
  382. /// </summary>
  383. /// <param name="inputStream">The seekable input stream containing the zip to extract from.</param>
  384. /// <param name="targetDirectory">The directory to save extracted information in.</param>
  385. /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
  386. /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
  387. /// <param name="fileFilter">A filter to apply to files.</param>
  388. /// <param name="directoryFilter">A filter to apply to directories.</param>
  389. /// <param name="restoreDateTime">Flag indicating whether to restore the date and time for extracted files.</param>
  390. /// <param name="isStreamOwner">Flag indicating whether the inputStream will be closed by this method.</param>
  391. /// <param name="allowParentTraversal">Allow parent directory traversal in file paths (e.g. ../file)</param>
  392. public void ExtractZip(Stream inputStream, string targetDirectory,
  393. Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate,
  394. string fileFilter, string directoryFilter, bool restoreDateTime,
  395. bool isStreamOwner, bool allowParentTraversal = false)
  396. {
  397. if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
  398. {
  399. throw new ArgumentNullException(nameof(confirmDelegate));
  400. }
  401. continueRunning_ = true;
  402. overwrite_ = overwrite;
  403. confirmDelegate_ = confirmDelegate;
  404. extractNameTransform_ = new WindowsNameTransform(targetDirectory, allowParentTraversal);
  405. fileFilter_ = new NameFilter(fileFilter);
  406. directoryFilter_ = new NameFilter(directoryFilter);
  407. restoreDateTimeOnExtract_ = restoreDateTime;
  408. using (zipFile_ = new ZipFile(inputStream, !isStreamOwner))
  409. {
  410. if (password_ != null)
  411. {
  412. zipFile_.Password = password_;
  413. }
  414. System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator();
  415. while (continueRunning_ && enumerator.MoveNext())
  416. {
  417. var entry = (ZipEntry)enumerator.Current;
  418. if (entry.IsFile)
  419. {
  420. // TODO Path.GetDirectory can fail here on invalid characters.
  421. if (directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name))
  422. {
  423. ExtractEntry(entry);
  424. }
  425. }
  426. else if (entry.IsDirectory)
  427. {
  428. if (directoryFilter_.IsMatch(entry.Name) && CreateEmptyDirectories)
  429. {
  430. ExtractEntry(entry);
  431. }
  432. }
  433. else
  434. {
  435. // Do nothing for volume labels etc...
  436. }
  437. }
  438. }
  439. }
  440. #endregion ExtractZip
  441. #region Internal Processing
  442. private void ProcessDirectory(object sender, DirectoryEventArgs e)
  443. {
  444. if (!e.HasMatchingFiles && CreateEmptyDirectories)
  445. {
  446. if (events_ != null)
  447. {
  448. events_.OnProcessDirectory(e.Name, e.HasMatchingFiles);
  449. }
  450. if (e.ContinueRunning)
  451. {
  452. if (e.Name != sourceDirectory_)
  453. {
  454. ZipEntry entry = entryFactory_.MakeDirectoryEntry(e.Name);
  455. outputStream_.PutNextEntry(entry);
  456. }
  457. }
  458. }
  459. }
  460. private void ProcessFile(object sender, ScanEventArgs e)
  461. {
  462. if ((events_ != null) && (events_.ProcessFile != null))
  463. {
  464. events_.ProcessFile(sender, e);
  465. }
  466. if (e.ContinueRunning)
  467. {
  468. try
  469. {
  470. // The open below is equivalent to OpenRead which gaurantees that if opened the
  471. // file will not be changed by subsequent openers, but precludes opening in some cases
  472. // were it could succeed. ie the open may fail as its already open for writing and the share mode should reflect that.
  473. using (FileStream stream = File.Open(e.Name, FileMode.Open, FileAccess.Read, FileShare.Read))
  474. {
  475. ZipEntry entry = entryFactory_.MakeFileEntry(e.Name);
  476. outputStream_.PutNextEntry(entry);
  477. AddFileContents(e.Name, stream);
  478. }
  479. }
  480. catch (Exception ex)
  481. {
  482. if (events_ != null)
  483. {
  484. continueRunning_ = events_.OnFileFailure(e.Name, ex);
  485. }
  486. else
  487. {
  488. continueRunning_ = false;
  489. throw;
  490. }
  491. }
  492. }
  493. }
  494. private void AddFileContents(string name, Stream stream)
  495. {
  496. if (stream == null)
  497. {
  498. throw new ArgumentNullException(nameof(stream));
  499. }
  500. if (buffer_ == null)
  501. {
  502. buffer_ = new byte[4096];
  503. }
  504. if ((events_ != null) && (events_.Progress != null))
  505. {
  506. StreamUtils.Copy(stream, outputStream_, buffer_,
  507. events_.Progress, events_.ProgressInterval, this, name);
  508. }
  509. else
  510. {
  511. StreamUtils.Copy(stream, outputStream_, buffer_);
  512. }
  513. if (events_ != null)
  514. {
  515. continueRunning_ = events_.OnCompletedFile(name);
  516. }
  517. }
  518. private void ExtractFileEntry(ZipEntry entry, string targetName)
  519. {
  520. bool proceed = true;
  521. if (overwrite_ != Overwrite.Always)
  522. {
  523. if (File.Exists(targetName))
  524. {
  525. if ((overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null))
  526. {
  527. proceed = confirmDelegate_(targetName);
  528. }
  529. else
  530. {
  531. proceed = false;
  532. }
  533. }
  534. }
  535. if (proceed)
  536. {
  537. if (events_ != null)
  538. {
  539. continueRunning_ = events_.OnProcessFile(entry.Name);
  540. }
  541. if (continueRunning_)
  542. {
  543. try
  544. {
  545. using (FileStream outputStream = File.Create(targetName))
  546. {
  547. if (buffer_ == null)
  548. {
  549. buffer_ = new byte[4096];
  550. }
  551. if ((events_ != null) && (events_.Progress != null))
  552. {
  553. StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_,
  554. events_.Progress, events_.ProgressInterval, this, entry.Name, entry.Size);
  555. }
  556. else
  557. {
  558. StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_);
  559. }
  560. if (events_ != null)
  561. {
  562. continueRunning_ = events_.OnCompletedFile(entry.Name);
  563. }
  564. }
  565. if (restoreDateTimeOnExtract_)
  566. {
  567. File.SetLastWriteTime(targetName, entry.DateTime);
  568. }
  569. if (RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1))
  570. {
  571. var fileAttributes = (FileAttributes)entry.ExternalFileAttributes;
  572. // TODO: FastZip - Setting of other file attributes on extraction is a little trickier.
  573. fileAttributes &= (FileAttributes.Archive | FileAttributes.Normal | FileAttributes.ReadOnly | FileAttributes.Hidden);
  574. File.SetAttributes(targetName, fileAttributes);
  575. }
  576. }
  577. catch (Exception ex)
  578. {
  579. if (events_ != null)
  580. {
  581. continueRunning_ = events_.OnFileFailure(targetName, ex);
  582. }
  583. else
  584. {
  585. continueRunning_ = false;
  586. throw;
  587. }
  588. }
  589. }
  590. }
  591. }
  592. private void ExtractEntry(ZipEntry entry)
  593. {
  594. bool doExtraction = entry.IsCompressionMethodSupported();
  595. string targetName = entry.Name;
  596. if (doExtraction)
  597. {
  598. if (entry.IsFile)
  599. {
  600. targetName = extractNameTransform_.TransformFile(targetName);
  601. }
  602. else if (entry.IsDirectory)
  603. {
  604. targetName = extractNameTransform_.TransformDirectory(targetName);
  605. }
  606. doExtraction = !(string.IsNullOrEmpty(targetName));
  607. }
  608. // TODO: Fire delegate/throw exception were compression method not supported, or name is invalid?
  609. string dirName = null;
  610. if (doExtraction)
  611. {
  612. if (entry.IsDirectory)
  613. {
  614. dirName = targetName;
  615. }
  616. else
  617. {
  618. dirName = Path.GetDirectoryName(Path.GetFullPath(targetName));
  619. }
  620. }
  621. if (doExtraction && !Directory.Exists(dirName))
  622. {
  623. if (!entry.IsDirectory || CreateEmptyDirectories)
  624. {
  625. try
  626. {
  627. Directory.CreateDirectory(dirName);
  628. }
  629. catch (Exception ex)
  630. {
  631. doExtraction = false;
  632. if (events_ != null)
  633. {
  634. if (entry.IsDirectory)
  635. {
  636. continueRunning_ = events_.OnDirectoryFailure(targetName, ex);
  637. }
  638. else
  639. {
  640. continueRunning_ = events_.OnFileFailure(targetName, ex);
  641. }
  642. }
  643. else
  644. {
  645. continueRunning_ = false;
  646. throw;
  647. }
  648. }
  649. }
  650. }
  651. if (doExtraction && entry.IsFile)
  652. {
  653. ExtractFileEntry(entry, targetName);
  654. }
  655. }
  656. private static int MakeExternalAttributes(FileInfo info)
  657. {
  658. return (int)info.Attributes;
  659. }
  660. private static bool NameIsValid(string name)
  661. {
  662. return !string.IsNullOrEmpty(name) &&
  663. (name.IndexOfAny(Path.GetInvalidPathChars()) < 0);
  664. }
  665. #endregion Internal Processing
  666. #region Instance Fields
  667. private bool continueRunning_;
  668. private byte[] buffer_;
  669. private ZipOutputStream outputStream_;
  670. private ZipFile zipFile_;
  671. private string sourceDirectory_;
  672. private NameFilter fileFilter_;
  673. private NameFilter directoryFilter_;
  674. private Overwrite overwrite_;
  675. private ConfirmOverwriteDelegate confirmDelegate_;
  676. private bool restoreDateTimeOnExtract_;
  677. private bool restoreAttributesOnExtract_;
  678. private bool createEmptyDirectories_;
  679. private FastZipEvents events_;
  680. private IEntryFactory entryFactory_ = new ZipEntryFactory();
  681. private INameTransform extractNameTransform_;
  682. private UseZip64 useZip64_ = UseZip64.Dynamic;
  683. private CompressionLevel compressionLevel_ = CompressionLevel.DEFAULT_COMPRESSION;
  684. private string password_;
  685. #endregion Instance Fields
  686. }
  687. }