ArchiveUpdateCallbackWithFileTime.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. #if UNMANAGED
  2. using System.Runtime.InteropServices;
  3. namespace SevenZip;
  4. public record CompressStreamEntry(Stream? Stream, DateTimeOffset? CreateTime, DateTimeOffset? LastWrite, DateTimeOffset? LastAccess)
  5. {
  6. public CompressStreamEntry(Stream? Stream, DateTimeOffset? fileTime) : this(Stream, fileTime, fileTime, fileTime)
  7. {
  8. }
  9. }
  10. internal sealed class ArchiveUpdateCallbackWithFileTime : CallbackBase, IArchiveUpdateCallback, ICryptoGetTextPassword2,
  11. IDisposable
  12. {
  13. #region Fields
  14. /// <summary>
  15. /// _files.Count if do not count directories
  16. /// </summary>
  17. private int _actualFilesCount;
  18. /// <summary>
  19. /// For Compressing event.
  20. /// </summary>
  21. private long _bytesCount;
  22. private long _bytesWritten;
  23. private long _bytesWrittenOld;
  24. private SevenZipCompressor _compressor;
  25. /// <summary>
  26. /// No directories.
  27. /// </summary>
  28. private bool _directoryStructure;
  29. /// <summary>
  30. /// Rate of the done work from [0, 1]
  31. /// </summary>
  32. private float _doneRate;
  33. /// <summary>
  34. /// The names of the archive entries
  35. /// </summary>
  36. private string[] _entries;
  37. /// <summary>
  38. /// Array of files to pack
  39. /// </summary>
  40. private FileInfo[]? _files;
  41. private InStreamWrapper _fileStream;
  42. private uint _indexInArchive;
  43. private uint _indexOffset;
  44. /// <summary>
  45. /// Common root of file names length.
  46. /// </summary>
  47. private int _rootLength;
  48. /// <summary>
  49. /// Input streams to be compressed.
  50. /// </summary>
  51. private CompressStreamEntry[] _streamEntries;
  52. private UpdateData _updateData;
  53. private List<InStreamWrapper> _wrappersToDispose;
  54. /// <summary>
  55. /// Gets or sets the default item name used in MemoryStream compression.
  56. /// </summary>
  57. public string DefaultItemName { private get; set; }
  58. /// <summary>
  59. /// Gets or sets the value indicating whether to compress as fast as possible, without calling events.
  60. /// </summary>
  61. public bool FastCompression { private get; set; }
  62. private int _memoryPressure;
  63. #endregion
  64. #region Constructors
  65. /// <summary>
  66. /// Initializes a new instance of the ArchiveUpdateCallback class
  67. /// </summary>
  68. /// <param name="files">Array of files to pack</param>
  69. /// <param name="rootLength">Common file names root length</param>
  70. /// <param name="compressor">The owner of the callback</param>
  71. /// <param name="updateData">The compression parameters.</param>
  72. /// <param name="directoryStructure">Preserve directory structure.</param>
  73. public ArchiveUpdateCallbackWithFileTime(
  74. FileInfo[] files, int rootLength,
  75. SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
  76. {
  77. Init(files, rootLength, compressor, updateData, directoryStructure);
  78. }
  79. /// <summary>
  80. /// Initializes a new instance of the ArchiveUpdateCallback class
  81. /// </summary>
  82. /// <param name="files">Array of files to pack</param>
  83. /// <param name="rootLength">Common file names root length</param>
  84. /// <param name="password">The archive password</param>
  85. /// <param name="compressor">The owner of the callback</param>
  86. /// <param name="updateData">The compression parameters.</param>
  87. /// <param name="directoryStructure">Preserve directory structure.</param>
  88. public ArchiveUpdateCallbackWithFileTime(
  89. FileInfo[] files, int rootLength, string password,
  90. SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
  91. : base(password)
  92. {
  93. Init(files, rootLength, compressor, updateData, directoryStructure);
  94. }
  95. /// <summary>
  96. /// Initializes a new instance of the ArchiveUpdateCallback class
  97. /// </summary>
  98. /// <param name="stream">The input stream</param>
  99. /// <param name="compressor">The owner of the callback</param>
  100. /// <param name="updateData">The compression parameters.</param>
  101. /// <param name="directoryStructure">Preserve directory structure.</param>
  102. public ArchiveUpdateCallbackWithFileTime(
  103. Stream stream, SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
  104. {
  105. Init(stream, compressor, updateData, directoryStructure);
  106. }
  107. /// <summary>
  108. /// Initializes a new instance of the ArchiveUpdateCallback class
  109. /// </summary>
  110. /// <param name="stream">The input stream</param>
  111. /// <param name="password">The archive password</param>
  112. /// <param name="compressor">The owner of the callback</param>
  113. /// <param name="updateData">The compression parameters.</param>
  114. /// <param name="directoryStructure">Preserve directory structure.</param>
  115. public ArchiveUpdateCallbackWithFileTime(
  116. Stream stream, string password, SevenZipCompressor compressor, UpdateData updateData,
  117. bool directoryStructure)
  118. : base(password)
  119. {
  120. Init(stream, compressor, updateData, directoryStructure);
  121. }
  122. /// <summary>
  123. /// Initializes a new instance of the ArchiveUpdateCallback class
  124. /// </summary>
  125. /// <param name="streamDict">Dictionary&lt;file stream, name of the archive entry&gt;</param>
  126. /// <param name="compressor">The owner of the callback</param>
  127. /// <param name="updateData">The compression parameters.</param>
  128. /// <param name="directoryStructure">Preserve directory structure.</param>
  129. public ArchiveUpdateCallbackWithFileTime(
  130. IDictionary<string, CompressStreamEntry> streamDict,
  131. SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
  132. {
  133. Init(streamDict, compressor, updateData, directoryStructure);
  134. }
  135. /// <summary>
  136. /// Initializes a new instance of the ArchiveUpdateCallback class
  137. /// </summary>
  138. /// <param name="streamDict">Dictionary&lt;file stream, name of the archive entry&gt;</param>
  139. /// <param name="password">The archive password</param>
  140. /// <param name="compressor">The owner of the callback</param>
  141. /// <param name="updateData">The compression parameters.</param>
  142. /// <param name="directoryStructure">Preserve directory structure.</param>
  143. public ArchiveUpdateCallbackWithFileTime(
  144. IDictionary<string, CompressStreamEntry> streamDict, string password,
  145. SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
  146. : base(password)
  147. {
  148. Init(streamDict, compressor, updateData, directoryStructure);
  149. }
  150. private void CommonInit(SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
  151. {
  152. _compressor = compressor;
  153. _indexInArchive = updateData.FilesCount;
  154. _indexOffset = updateData.Mode != InternalCompressionMode.Append ? 0 : _indexInArchive;
  155. if (_compressor.ArchiveFormat == OutArchiveFormat.Zip)
  156. {
  157. _wrappersToDispose = new List<InStreamWrapper>();
  158. }
  159. _updateData = updateData;
  160. _directoryStructure = directoryStructure;
  161. DefaultItemName = "default";
  162. }
  163. private void Init(
  164. FileInfo[] files, int rootLength, SevenZipCompressor compressor,
  165. UpdateData updateData, bool directoryStructure)
  166. {
  167. _files = files;
  168. _rootLength = rootLength;
  169. if (files != null)
  170. {
  171. foreach (var fi in files)
  172. {
  173. if (fi.Exists)
  174. {
  175. _bytesCount += fi.Length;
  176. if ((fi.Attributes & FileAttributes.Directory) == 0)
  177. {
  178. _actualFilesCount++;
  179. }
  180. }
  181. }
  182. }
  183. CommonInit(compressor, updateData, directoryStructure);
  184. }
  185. private void Init(
  186. Stream stream, SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
  187. {
  188. _fileStream = new InStreamWrapper(stream, false);
  189. _fileStream.BytesRead += IntEventArgsHandler;
  190. _actualFilesCount = 1;
  191. try
  192. {
  193. _bytesCount = stream.Length;
  194. }
  195. catch (NotSupportedException)
  196. {
  197. _bytesCount = -1;
  198. }
  199. try
  200. {
  201. stream.Seek(0, SeekOrigin.Begin);
  202. }
  203. catch (NotSupportedException)
  204. {
  205. _bytesCount = -1;
  206. }
  207. CommonInit(compressor, updateData, directoryStructure);
  208. }
  209. private void Init(
  210. IDictionary<string, CompressStreamEntry> streamDict,
  211. SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
  212. {
  213. _streamEntries = new CompressStreamEntry[streamDict.Count];
  214. streamDict.Values.ToArray().CopyTo(_streamEntries, 0);
  215. _entries = new string[streamDict.Count];
  216. streamDict.Keys.CopyTo(_entries, 0);
  217. _actualFilesCount = streamDict.Count;
  218. foreach (var entry in _streamEntries)
  219. {
  220. if (entry.Stream != null)
  221. {
  222. _bytesCount += entry.Stream.Length;
  223. }
  224. }
  225. CommonInit(compressor, updateData, directoryStructure);
  226. }
  227. #endregion
  228. /// <summary>
  229. /// Gets or sets the dictionary size.
  230. /// </summary>
  231. public float DictionarySize
  232. {
  233. set
  234. {
  235. _memoryPressure = (int)(value * 1024 * 1024);
  236. GC.AddMemoryPressure(_memoryPressure);
  237. }
  238. }
  239. /// <summary>
  240. /// Raises events for the GetStream method.
  241. /// </summary>
  242. /// <param name="index">The current item index.</param>
  243. /// <returns>True if not cancelled; otherwise, false.</returns>
  244. private bool EventsForGetStream(uint index)
  245. {
  246. if (!FastCompression)
  247. {
  248. if (_fileStream != null)
  249. {
  250. _fileStream.BytesRead += IntEventArgsHandler;
  251. }
  252. _doneRate += 1.0f / _actualFilesCount;
  253. var fiea = new FileNameEventArgs(_files != null ? _files[index].Name : _entries[index],
  254. PercentDoneEventArgs.ProducePercentDone(_doneRate));
  255. OnFileCompression(fiea);
  256. if (fiea.Cancel)
  257. {
  258. Canceled = true;
  259. return false;
  260. }
  261. }
  262. return true;
  263. }
  264. #region Events
  265. /// <summary>
  266. /// Occurs when the next file is going to be packed.
  267. /// </summary>
  268. /// <remarks>Occurs when 7-zip engine requests for an input stream for the next file to pack it</remarks>
  269. public event EventHandler<FileNameEventArgs> FileCompressionStarted;
  270. /// <summary>
  271. /// Occurs when data are being compressed.
  272. /// </summary>
  273. public event EventHandler<ProgressEventArgs> Compressing;
  274. /// <summary>
  275. /// Occurs when the current file was compressed.
  276. /// </summary>
  277. public event EventHandler FileCompressionFinished;
  278. private void OnFileCompression(FileNameEventArgs e)
  279. {
  280. FileCompressionStarted?.Invoke(this, e);
  281. }
  282. private void OnCompressing(ProgressEventArgs e)
  283. {
  284. Compressing?.Invoke(this, e);
  285. }
  286. private void OnFileCompressionFinished(EventArgs e)
  287. {
  288. FileCompressionFinished?.Invoke(this, e);
  289. }
  290. #endregion
  291. #region IArchiveUpdateCallback Members
  292. public void SetTotal(ulong total) { }
  293. public void SetCompleted(ref ulong completeValue) { }
  294. public int GetUpdateItemInfo(uint index, ref int newData, ref int newProperties, ref uint indexInArchive)
  295. {
  296. switch (_updateData.Mode)
  297. {
  298. case InternalCompressionMode.Create:
  299. newData = 1;
  300. newProperties = 1;
  301. indexInArchive = uint.MaxValue;
  302. break;
  303. case InternalCompressionMode.Append:
  304. if (index < _indexInArchive)
  305. {
  306. newData = 0;
  307. newProperties = 0;
  308. indexInArchive = index;
  309. }
  310. else
  311. {
  312. newData = 1;
  313. newProperties = 1;
  314. indexInArchive = uint.MaxValue;
  315. }
  316. break;
  317. case InternalCompressionMode.Modify:
  318. newData = 0;
  319. newProperties = Convert.ToInt32(_updateData.FileNamesToModify.ContainsKey((int)index)
  320. && _updateData.FileNamesToModify[(int)index] != null);
  321. if (_updateData.FileNamesToModify.ContainsKey((int)index)
  322. && _updateData.FileNamesToModify[(int)index] == null)
  323. {
  324. indexInArchive = (uint)_updateData.ArchiveFileData.Count;
  325. foreach (var pairModification in _updateData.FileNamesToModify)
  326. {
  327. if (pairModification.Key <= index && (pairModification.Value == null))
  328. {
  329. do
  330. {
  331. indexInArchive--;
  332. } while (indexInArchive > 0
  333. && _updateData.FileNamesToModify.ContainsKey((int)indexInArchive)
  334. && _updateData.FileNamesToModify[(int)indexInArchive] == null);
  335. }
  336. }
  337. }
  338. else
  339. {
  340. indexInArchive = index;
  341. }
  342. break;
  343. }
  344. return 0;
  345. }
  346. public int GetProperty(uint index, ItemPropId propID, ref PropVariant value)
  347. {
  348. index -= _indexOffset;
  349. try
  350. {
  351. switch (propID)
  352. {
  353. case ItemPropId.IsAnti:
  354. value.VarType = VarEnum.VT_BOOL;
  355. value.UInt64Value = 0;
  356. break;
  357. case ItemPropId.Path:
  358. #region Path
  359. value.VarType = VarEnum.VT_BSTR;
  360. string val = DefaultItemName;
  361. if (_updateData.Mode != InternalCompressionMode.Modify)
  362. {
  363. if (_files == null)
  364. {
  365. if (_entries != null)
  366. {
  367. val = _entries[index];
  368. }
  369. }
  370. else
  371. {
  372. if (_directoryStructure)
  373. {
  374. if (_rootLength > 0)
  375. {
  376. val = _files[index].FullName.Substring(_rootLength);
  377. }
  378. else
  379. {
  380. val = _files[index].FullName[0] + _files[index].FullName.Substring(2);
  381. }
  382. }
  383. else
  384. {
  385. val = _files[index].Name;
  386. }
  387. }
  388. }
  389. else
  390. {
  391. val = _updateData.FileNamesToModify[(int)index];
  392. }
  393. value.Value = Marshal.StringToBSTR(val);
  394. #endregion
  395. break;
  396. case ItemPropId.IsDirectory:
  397. value.VarType = VarEnum.VT_BOOL;
  398. if (_updateData.Mode != InternalCompressionMode.Modify)
  399. {
  400. if (_files == null)
  401. {
  402. if (_streamEntries == null)
  403. {
  404. value.UInt64Value = 0;
  405. }
  406. else
  407. {
  408. value.UInt64Value = (ulong)(_streamEntries[index] == null ? 1 : 0);
  409. }
  410. }
  411. else
  412. {
  413. value.UInt64Value = (byte)(_files[index].Attributes & FileAttributes.Directory);
  414. }
  415. }
  416. else
  417. {
  418. value.UInt64Value = Convert.ToUInt64(_updateData.ArchiveFileData[(int)index].IsDirectory);
  419. }
  420. break;
  421. case ItemPropId.Size:
  422. #region Size
  423. value.VarType = VarEnum.VT_UI8;
  424. ulong size;
  425. if (_updateData.Mode != InternalCompressionMode.Modify)
  426. {
  427. if (_files == null)
  428. {
  429. if (_streamEntries == null)
  430. {
  431. size = _bytesCount > 0 ? (ulong)_bytesCount : 0;
  432. }
  433. else
  434. {
  435. size = (ulong)(_streamEntries[index].Stream == null ? 0 : _streamEntries[index].Stream.Length);
  436. }
  437. }
  438. else
  439. {
  440. size = (_files[index].Attributes & FileAttributes.Directory) == 0
  441. ? (ulong)_files[index].Length
  442. : 0;
  443. }
  444. }
  445. else
  446. {
  447. size = _updateData.ArchiveFileData[(int)index].Size;
  448. }
  449. value.UInt64Value = size;
  450. #endregion
  451. break;
  452. case ItemPropId.Attributes:
  453. value.VarType = VarEnum.VT_UI4;
  454. if (_updateData.Mode != InternalCompressionMode.Modify)
  455. {
  456. if (_files == null)
  457. {
  458. if (_streamEntries == null)
  459. {
  460. value.UInt32Value = (uint)FileAttributes.Normal;
  461. }
  462. else
  463. {
  464. value.UInt32Value = (uint)(_streamEntries[index].Stream == null ? FileAttributes.Directory : FileAttributes.Normal);
  465. }
  466. }
  467. else
  468. {
  469. value.UInt32Value = (uint)_files[index].Attributes;
  470. }
  471. }
  472. else
  473. {
  474. value.UInt32Value = _updateData.ArchiveFileData[(int)index].Attributes;
  475. }
  476. break;
  477. #region Times
  478. case ItemPropId.CreationTime:
  479. value.VarType = VarEnum.VT_FILETIME;
  480. if (_updateData.Mode != InternalCompressionMode.Modify)
  481. {
  482. if (_files != null)
  483. value.Int64Value = _files[index].CreationTime.ToFileTime();
  484. else if (_streamEntries != null && _streamEntries[index].CreateTime.HasValue)
  485. value.Int64Value = _streamEntries[index].CreateTime.Value.ToFileTime();
  486. else
  487. value.Int64Value = DateTime.Now.ToFileTime();
  488. }
  489. else
  490. {
  491. value.Int64Value = _updateData.ArchiveFileData[(int)index].CreationTime.ToFileTime();
  492. }
  493. break;
  494. case ItemPropId.LastAccessTime:
  495. value.VarType = VarEnum.VT_FILETIME;
  496. if (_updateData.Mode != InternalCompressionMode.Modify)
  497. {
  498. if (_files != null)
  499. value.Int64Value = _files[index].LastAccessTime.ToFileTime();
  500. else if (_streamEntries != null && _streamEntries[index].LastAccess.HasValue)
  501. value.Int64Value = _streamEntries[index].LastAccess.Value.ToFileTime();
  502. else
  503. value.Int64Value = DateTime.Now.ToFileTime();
  504. }
  505. else
  506. {
  507. value.Int64Value = _updateData.ArchiveFileData[(int)index].LastAccessTime.ToFileTime();
  508. }
  509. break;
  510. case ItemPropId.LastWriteTime:
  511. value.VarType = VarEnum.VT_FILETIME;
  512. if (_updateData.Mode != InternalCompressionMode.Modify)
  513. {
  514. if (_files == null)
  515. value.Int64Value = DateTime.Now.ToFileTime();
  516. else if (_streamEntries != null && _streamEntries[index].LastWrite.HasValue)
  517. value.Int64Value = _streamEntries[index].LastWrite.Value.ToFileTime();
  518. else
  519. value.Int64Value = _files[index].LastWriteTime.ToFileTime();
  520. }
  521. else
  522. {
  523. value.Int64Value = _updateData.ArchiveFileData[(int)index].LastWriteTime.ToFileTime();
  524. }
  525. break;
  526. #endregion
  527. case ItemPropId.Extension:
  528. #region Extension
  529. value.VarType = VarEnum.VT_BSTR;
  530. if (_updateData.Mode != InternalCompressionMode.Modify)
  531. {
  532. try
  533. {
  534. val = _files != null
  535. ? _files[index].Extension.Substring(1)
  536. : _entries == null
  537. ? ""
  538. : Path.GetExtension(_entries[index]);
  539. value.Value = Marshal.StringToBSTR(val);
  540. }
  541. catch (ArgumentException)
  542. {
  543. value.Value = Marshal.StringToBSTR("");
  544. }
  545. }
  546. else
  547. {
  548. val = Path.GetExtension(_updateData.ArchiveFileData[(int)index].FileName);
  549. value.Value = Marshal.StringToBSTR(val);
  550. }
  551. #endregion
  552. break;
  553. }
  554. }
  555. catch (Exception e)
  556. {
  557. AddException(e);
  558. }
  559. return 0;
  560. }
  561. /// <summary>
  562. /// Gets the stream for 7-zip library.
  563. /// </summary>
  564. /// <param name="index">File index</param>
  565. /// <param name="inStream">Input file stream</param>
  566. /// <returns>Zero if Ok</returns>
  567. public int GetStream(uint index, out ISequentialInStream inStream)
  568. {
  569. index -= _indexOffset;
  570. if (_files != null)
  571. {
  572. _fileStream = null;
  573. try
  574. {
  575. if (File.Exists(_files[index].FullName))
  576. {
  577. _fileStream = new InStreamWrapper(
  578. new FileStream(_files[index].FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),
  579. true);
  580. }
  581. }
  582. catch (Exception e)
  583. {
  584. AddException(e);
  585. inStream = null;
  586. return -1;
  587. }
  588. inStream = _fileStream;
  589. if (!EventsForGetStream(index))
  590. {
  591. return -1;
  592. }
  593. }
  594. else
  595. {
  596. if (_streamEntries == null)
  597. {
  598. inStream = _fileStream;
  599. }
  600. else
  601. {
  602. _fileStream = new InStreamWrapper(_streamEntries[index].Stream, true);
  603. inStream = _fileStream;
  604. if (!EventsForGetStream(index))
  605. {
  606. return -1;
  607. }
  608. }
  609. }
  610. return 0;
  611. }
  612. public long EnumProperties(IntPtr enumerator)
  613. {
  614. //Not implemented HRESULT
  615. return 0x80004001L;
  616. }
  617. public void SetOperationResult(OperationResult operationResult)
  618. {
  619. if (operationResult != OperationResult.Ok && ReportErrors)
  620. {
  621. switch (operationResult)
  622. {
  623. case OperationResult.CrcError:
  624. AddException(new ExtractionFailedException("File is corrupted. Crc check has failed."));
  625. break;
  626. case OperationResult.DataError:
  627. AddException(new ExtractionFailedException("File is corrupted. Data error has occurred."));
  628. break;
  629. case OperationResult.UnsupportedMethod:
  630. AddException(new ExtractionFailedException("Unsupported method error has occurred."));
  631. break;
  632. case OperationResult.Unavailable:
  633. AddException(new ExtractionFailedException("File is unavailable."));
  634. break;
  635. case OperationResult.UnexpectedEnd:
  636. AddException(new ExtractionFailedException("Unexpected end of file."));
  637. break;
  638. case OperationResult.DataAfterEnd:
  639. AddException(new ExtractionFailedException("Data after end of archive."));
  640. break;
  641. case OperationResult.IsNotArc:
  642. AddException(new ExtractionFailedException("File is not archive."));
  643. break;
  644. case OperationResult.HeadersError:
  645. AddException(new ExtractionFailedException("Archive headers error."));
  646. break;
  647. case OperationResult.WrongPassword:
  648. AddException(new ExtractionFailedException("Wrong password."));
  649. break;
  650. default:
  651. AddException(new ExtractionFailedException($"Unexpected operation result: {operationResult}"));
  652. break;
  653. }
  654. }
  655. if (_fileStream != null)
  656. {
  657. _fileStream.BytesRead -= IntEventArgsHandler;
  658. //Specific Zip implementation - can not Dispose files for Zip.
  659. if (_compressor.ArchiveFormat != OutArchiveFormat.Zip)
  660. {
  661. try
  662. {
  663. _fileStream.Dispose();
  664. }
  665. catch (ObjectDisposedException) { }
  666. }
  667. else
  668. {
  669. _wrappersToDispose.Add(_fileStream);
  670. }
  671. _fileStream = null;
  672. }
  673. OnFileCompressionFinished(EventArgs.Empty);
  674. }
  675. #endregion
  676. #region ICryptoGetTextPassword2 Members
  677. public int CryptoGetTextPassword2(ref int passwordIsDefined, out string password)
  678. {
  679. passwordIsDefined = string.IsNullOrEmpty(Password) ? 0 : 1;
  680. password = Password;
  681. return 0;
  682. }
  683. #endregion
  684. #region IDisposable Members
  685. public void Dispose()
  686. {
  687. GC.RemoveMemoryPressure(_memoryPressure);
  688. if (_fileStream != null)
  689. {
  690. try
  691. {
  692. _fileStream.Dispose();
  693. }
  694. catch (ObjectDisposedException) { }
  695. }
  696. if (_wrappersToDispose == null)
  697. {
  698. return;
  699. }
  700. foreach (var wrapper in _wrappersToDispose)
  701. {
  702. try
  703. {
  704. wrapper.Dispose();
  705. }
  706. catch (ObjectDisposedException) { }
  707. }
  708. }
  709. #endregion
  710. private void IntEventArgsHandler(object sender, IntEventArgs e)
  711. {
  712. var lockObject = ((object)_files ?? _streamEntries) ?? _fileStream;
  713. lock (lockObject)
  714. {
  715. var pOld = (byte)(_bytesWrittenOld * 100 / _bytesCount);
  716. _bytesWritten += e.Value;
  717. byte pNow;
  718. if (_bytesCount < _bytesWritten) //Holy shit, this check for ZIP is golden
  719. {
  720. pNow = 100;
  721. }
  722. else
  723. {
  724. pNow = (byte)((_bytesWritten * 100) / _bytesCount);
  725. }
  726. if (pNow > pOld)
  727. {
  728. _bytesWrittenOld = _bytesWritten;
  729. OnCompressing(new ProgressEventArgs(pNow, (byte)(pNow - pOld)));
  730. }
  731. }
  732. }
  733. }
  734. #endif