forked from svn2github/dotnetzip
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZipFile.Events.cs
More file actions
1219 lines (1175 loc) · 49.3 KB
/
Copy pathZipFile.Events.cs
File metadata and controls
1219 lines (1175 loc) · 49.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ZipFile.Events.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2011 Dino Chiesa .
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-July-09 08:42:35>
//
// ------------------------------------------------------------------
//
// This module defines the methods for issuing events from the ZipFile class.
//
// ------------------------------------------------------------------
//
using System;
using System.IO;
namespace Ionic.Zip
{
public partial class ZipFile
{
private string ArchiveNameForEvent
{
get
{
return (_name != null) ? _name : "(stream)";
}
}
#region Save
/// <summary>
/// An event handler invoked when a Save() starts, before and after each
/// entry has been written to the archive, when a Save() completes, and
/// during other Save events.
/// </summary>
///
/// <remarks>
/// <para>
/// Depending on the particular event, different properties on the <see
/// cref="SaveProgressEventArgs"/> parameter are set. The following
/// table summarizes the available EventTypes and the conditions under
/// which this event handler is invoked with a
/// <c>SaveProgressEventArgs</c> with the given EventType.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>value of EntryType</term>
/// <description>Meaning and conditions</description>
/// </listheader>
///
/// <item>
/// <term>ZipProgressEventType.Saving_Started</term>
/// <description>Fired when ZipFile.Save() begins.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Saving_BeforeSaveEntry</term>
/// <description>
/// Fired within ZipFile.Save(), just before writing data for each
/// particular entry.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Saving_AfterSaveEntry</term>
/// <description>
/// Fired within ZipFile.Save(), just after having finished writing data
/// for each particular entry.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Saving_Completed</term>
/// <description>Fired when ZipFile.Save() has completed.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Saving_AfterSaveTempArchive</term>
/// <description>
/// Fired after the temporary file has been created. This happens only
/// when saving to a disk file. This event will not be invoked when
/// saving to a stream.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Saving_BeforeRenameTempArchive</term>
/// <description>
/// Fired just before renaming the temporary file to the permanent
/// location. This happens only when saving to a disk file. This event
/// will not be invoked when saving to a stream.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Saving_AfterRenameTempArchive</term>
/// <description>
/// Fired just after renaming the temporary file to the permanent
/// location. This happens only when saving to a disk file. This event
/// will not be invoked when saving to a stream.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Saving_AfterCompileSelfExtractor</term>
/// <description>
/// Fired after a self-extracting archive has finished compiling. This
/// EventType is used only within SaveSelfExtractor().
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Saving_BytesRead</term>
/// <description>
/// Set during the save of a particular entry, to update progress of the
/// Save(). When this EventType is set, the BytesTransferred is the
/// number of bytes that have been read from the source stream. The
/// TotalBytesToTransfer is the number of bytes in the uncompressed
/// file.
/// </description>
/// </item>
///
/// </list>
/// </remarks>
///
/// <example>
///
/// This example uses an anonymous method to handle the
/// SaveProgress event, by updating a progress bar.
///
/// <code lang="C#">
/// progressBar1.Value = 0;
/// progressBar1.Max = listbox1.Items.Count;
/// using (ZipFile zip = new ZipFile())
/// {
/// // listbox1 contains a list of filenames
/// zip.AddFiles(listbox1.Items);
///
/// // do the progress bar:
/// zip.SaveProgress += (sender, e) => {
/// if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry) {
/// progressBar1.PerformStep();
/// }
/// };
///
/// zip.Save(fs);
/// }
/// </code>
/// </example>
///
/// <example>
/// This example uses a named method as the
/// <c>SaveProgress</c> event handler, to update the user, in a
/// console-based application.
///
/// <code lang="C#">
/// static bool justHadByteUpdate= false;
/// public static void SaveProgress(object sender, SaveProgressEventArgs e)
/// {
/// if (e.EventType == ZipProgressEventType.Saving_Started)
/// Console.WriteLine("Saving: {0}", e.ArchiveName);
///
/// else if (e.EventType == ZipProgressEventType.Saving_Completed)
/// {
/// justHadByteUpdate= false;
/// Console.WriteLine();
/// Console.WriteLine("Done: {0}", e.ArchiveName);
/// }
///
/// else if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry)
/// {
/// if (justHadByteUpdate)
/// Console.WriteLine();
/// Console.WriteLine(" Writing: {0} ({1}/{2})",
/// e.CurrentEntry.FileName, e.EntriesSaved, e.EntriesTotal);
/// justHadByteUpdate= false;
/// }
///
/// else if (e.EventType == ZipProgressEventType.Saving_EntryBytesRead)
/// {
/// if (justHadByteUpdate)
/// Console.SetCursorPosition(0, Console.CursorTop);
/// Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, e.TotalBytesToTransfer,
/// e.BytesTransferred / (0.01 * e.TotalBytesToTransfer ));
/// justHadByteUpdate= true;
/// }
/// }
///
/// public static ZipUp(string targetZip, string directory)
/// {
/// using (var zip = new ZipFile()) {
/// zip.SaveProgress += SaveProgress;
/// zip.AddDirectory(directory);
/// zip.Save(targetZip);
/// }
/// }
///
/// </code>
///
/// <code lang="VB">
/// Public Sub ZipUp(ByVal targetZip As String, ByVal directory As String)
/// Using zip As ZipFile = New ZipFile
/// AddHandler zip.SaveProgress, AddressOf MySaveProgress
/// zip.AddDirectory(directory)
/// zip.Save(targetZip)
/// End Using
/// End Sub
///
/// Private Shared justHadByteUpdate As Boolean = False
///
/// Public Shared Sub MySaveProgress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
/// If (e.EventType Is ZipProgressEventType.Saving_Started) Then
/// Console.WriteLine("Saving: {0}", e.ArchiveName)
///
/// ElseIf (e.EventType Is ZipProgressEventType.Saving_Completed) Then
/// justHadByteUpdate = False
/// Console.WriteLine
/// Console.WriteLine("Done: {0}", e.ArchiveName)
///
/// ElseIf (e.EventType Is ZipProgressEventType.Saving_BeforeWriteEntry) Then
/// If justHadByteUpdate Then
/// Console.WriteLine
/// End If
/// Console.WriteLine(" Writing: {0} ({1}/{2})", e.CurrentEntry.FileName, e.EntriesSaved, e.EntriesTotal)
/// justHadByteUpdate = False
///
/// ElseIf (e.EventType Is ZipProgressEventType.Saving_EntryBytesRead) Then
/// If justHadByteUpdate Then
/// Console.SetCursorPosition(0, Console.CursorTop)
/// End If
/// Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, _
/// e.TotalBytesToTransfer, _
/// (CDbl(e.BytesTransferred) / (0.01 * e.TotalBytesToTransfer)))
/// justHadByteUpdate = True
/// End If
/// End Sub
/// </code>
/// </example>
///
/// <example>
///
/// This is a more complete example of using the SaveProgress
/// events in a Windows Forms application, with a
/// Thread object.
///
/// <code lang="C#">
/// delegate void SaveEntryProgress(SaveProgressEventArgs e);
/// delegate void ButtonClick(object sender, EventArgs e);
///
/// public class WorkerOptions
/// {
/// public string ZipName;
/// public string Folder;
/// public string Encoding;
/// public string Comment;
/// public int ZipFlavor;
/// public Zip64Option Zip64;
/// }
///
/// private int _progress2MaxFactor;
/// private bool _saveCanceled;
/// private long _totalBytesBeforeCompress;
/// private long _totalBytesAfterCompress;
/// private Thread _workerThread;
///
///
/// private void btnZipup_Click(object sender, EventArgs e)
/// {
/// KickoffZipup();
/// }
///
/// private void btnCancel_Click(object sender, EventArgs e)
/// {
/// if (this.lblStatus.InvokeRequired)
/// {
/// this.lblStatus.Invoke(new ButtonClick(this.btnCancel_Click), new object[] { sender, e });
/// }
/// else
/// {
/// _saveCanceled = true;
/// lblStatus.Text = "Canceled...";
/// ResetState();
/// }
/// }
///
/// private void KickoffZipup()
/// {
/// _folderName = tbDirName.Text;
///
/// if (_folderName == null || _folderName == "") return;
/// if (this.tbZipName.Text == null || this.tbZipName.Text == "") return;
///
/// // check for existence of the zip file:
/// if (System.IO.File.Exists(this.tbZipName.Text))
/// {
/// var dlgResult = MessageBox.Show(String.Format("The file you have specified ({0}) already exists." +
/// " Do you want to overwrite this file?", this.tbZipName.Text),
/// "Confirmation is Required", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
/// if (dlgResult != DialogResult.Yes) return;
/// System.IO.File.Delete(this.tbZipName.Text);
/// }
///
/// _saveCanceled = false;
/// _nFilesCompleted = 0;
/// _totalBytesAfterCompress = 0;
/// _totalBytesBeforeCompress = 0;
/// this.btnOk.Enabled = false;
/// this.btnOk.Text = "Zipping...";
/// this.btnCancel.Enabled = true;
/// lblStatus.Text = "Zipping...";
///
/// var options = new WorkerOptions
/// {
/// ZipName = this.tbZipName.Text,
/// Folder = _folderName,
/// Encoding = "ibm437"
/// };
///
/// if (this.comboBox1.SelectedIndex != 0)
/// {
/// options.Encoding = this.comboBox1.SelectedItem.ToString();
/// }
///
/// if (this.radioFlavorSfxCmd.Checked)
/// options.ZipFlavor = 2;
/// else if (this.radioFlavorSfxGui.Checked)
/// options.ZipFlavor = 1;
/// else options.ZipFlavor = 0;
///
/// if (this.radioZip64AsNecessary.Checked)
/// options.Zip64 = Zip64Option.AsNecessary;
/// else if (this.radioZip64Always.Checked)
/// options.Zip64 = Zip64Option.Always;
/// else options.Zip64 = Zip64Option.Never;
///
/// options.Comment = String.Format("Encoding:{0} || Flavor:{1} || ZIP64:{2}\r\nCreated at {3} || {4}\r\n",
/// options.Encoding,
/// FlavorToString(options.ZipFlavor),
/// options.Zip64.ToString(),
/// System.DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss"),
/// this.Text);
///
/// if (this.tbComment.Text != TB_COMMENT_NOTE)
/// options.Comment += this.tbComment.Text;
///
/// _workerThread = new Thread(this.DoSave);
/// _workerThread.Name = "Zip Saver thread";
/// _workerThread.Start(options);
/// this.Cursor = Cursors.WaitCursor;
/// }
///
///
/// private void DoSave(Object p)
/// {
/// WorkerOptions options = p as WorkerOptions;
/// try
/// {
/// using (var zip1 = new ZipFile())
/// {
/// zip1.ProvisionalAlternateEncoding = System.Text.Encoding.GetEncoding(options.Encoding);
/// zip1.Comment = options.Comment;
/// zip1.AddDirectory(options.Folder);
/// _entriesToZip = zip1.EntryFileNames.Count;
/// SetProgressBars();
/// zip1.SaveProgress += this.zip1_SaveProgress;
///
/// zip1.UseZip64WhenSaving = options.Zip64;
///
/// if (options.ZipFlavor == 1)
/// zip1.SaveSelfExtractor(options.ZipName, SelfExtractorFlavor.WinFormsApplication);
/// else if (options.ZipFlavor == 2)
/// zip1.SaveSelfExtractor(options.ZipName, SelfExtractorFlavor.ConsoleApplication);
/// else
/// zip1.Save(options.ZipName);
/// }
/// }
/// catch (System.Exception exc1)
/// {
/// MessageBox.Show(String.Format("Exception while zipping: {0}", exc1.Message));
/// btnCancel_Click(null, null);
/// }
/// }
///
///
///
/// void zip1_SaveProgress(object sender, SaveProgressEventArgs e)
/// {
/// switch (e.EventType)
/// {
/// case ZipProgressEventType.Saving_AfterWriteEntry:
/// StepArchiveProgress(e);
/// break;
/// case ZipProgressEventType.Saving_EntryBytesRead:
/// StepEntryProgress(e);
/// break;
/// case ZipProgressEventType.Saving_Completed:
/// SaveCompleted();
/// break;
/// case ZipProgressEventType.Saving_AfterSaveTempArchive:
/// // this event only occurs when saving an SFX file
/// TempArchiveSaved();
/// break;
/// }
/// if (_saveCanceled)
/// e.Cancel = true;
/// }
///
///
///
/// private void StepArchiveProgress(SaveProgressEventArgs e)
/// {
/// if (this.progressBar1.InvokeRequired)
/// {
/// this.progressBar1.Invoke(new SaveEntryProgress(this.StepArchiveProgress), new object[] { e });
/// }
/// else
/// {
/// if (!_saveCanceled)
/// {
/// _nFilesCompleted++;
/// this.progressBar1.PerformStep();
/// _totalBytesAfterCompress += e.CurrentEntry.CompressedSize;
/// _totalBytesBeforeCompress += e.CurrentEntry.UncompressedSize;
///
/// // reset the progress bar for the entry:
/// this.progressBar2.Value = this.progressBar2.Maximum = 1;
///
/// this.Update();
/// }
/// }
/// }
///
///
/// private void StepEntryProgress(SaveProgressEventArgs e)
/// {
/// if (this.progressBar2.InvokeRequired)
/// {
/// this.progressBar2.Invoke(new SaveEntryProgress(this.StepEntryProgress), new object[] { e });
/// }
/// else
/// {
/// if (!_saveCanceled)
/// {
/// if (this.progressBar2.Maximum == 1)
/// {
/// // reset
/// Int64 max = e.TotalBytesToTransfer;
/// _progress2MaxFactor = 0;
/// while (max > System.Int32.MaxValue)
/// {
/// max /= 2;
/// _progress2MaxFactor++;
/// }
/// this.progressBar2.Maximum = (int)max;
/// lblStatus.Text = String.Format("{0} of {1} files...({2})",
/// _nFilesCompleted + 1, _entriesToZip, e.CurrentEntry.FileName);
/// }
///
/// int xferred = e.BytesTransferred >> _progress2MaxFactor;
///
/// this.progressBar2.Value = (xferred >= this.progressBar2.Maximum)
/// ? this.progressBar2.Maximum
/// : xferred;
///
/// this.Update();
/// }
/// }
/// }
///
/// private void SaveCompleted()
/// {
/// if (this.lblStatus.InvokeRequired)
/// {
/// this.lblStatus.Invoke(new MethodInvoker(this.SaveCompleted));
/// }
/// else
/// {
/// lblStatus.Text = String.Format("Done, Compressed {0} files, {1:N0}% of original.",
/// _nFilesCompleted, (100.00 * _totalBytesAfterCompress) / _totalBytesBeforeCompress);
/// ResetState();
/// }
/// }
///
/// private void ResetState()
/// {
/// this.btnCancel.Enabled = false;
/// this.btnOk.Enabled = true;
/// this.btnOk.Text = "Zip it!";
/// this.progressBar1.Value = 0;
/// this.progressBar2.Value = 0;
/// this.Cursor = Cursors.Default;
/// if (!_workerThread.IsAlive)
/// _workerThread.Join();
/// }
/// </code>
///
/// </example>
///
/// <seealso cref="Ionic.Zip.ZipFile.ReadProgress"/>
/// <seealso cref="Ionic.Zip.ZipFile.AddProgress"/>
/// <seealso cref="Ionic.Zip.ZipFile.ExtractProgress"/>
public event EventHandler<SaveProgressEventArgs> SaveProgress;
internal bool OnSaveBlock(ZipEntry entry, Int64 bytesXferred, Int64 totalBytesToXfer)
{
EventHandler<SaveProgressEventArgs> sp = SaveProgress;
if (sp != null)
{
var e = SaveProgressEventArgs.ByteUpdate(ArchiveNameForEvent, entry,
bytesXferred, totalBytesToXfer);
sp(this, e);
if (e.Cancel)
_saveOperationCanceled = true;
}
return _saveOperationCanceled;
}
private void OnSaveEntry(int current, ZipEntry entry, bool before)
{
EventHandler<SaveProgressEventArgs> sp = SaveProgress;
if (sp != null)
{
var e = new SaveProgressEventArgs(ArchiveNameForEvent, before, _entries.Count, current, entry);
sp(this, e);
if (e.Cancel)
_saveOperationCanceled = true;
}
}
private void OnSaveEvent(ZipProgressEventType eventFlavor)
{
EventHandler<SaveProgressEventArgs> sp = SaveProgress;
if (sp != null)
{
var e = new SaveProgressEventArgs(ArchiveNameForEvent, eventFlavor);
sp(this, e);
if (e.Cancel)
_saveOperationCanceled = true;
}
}
private void OnSaveStarted()
{
EventHandler<SaveProgressEventArgs> sp = SaveProgress;
if (sp != null)
{
var e = SaveProgressEventArgs.Started(ArchiveNameForEvent);
sp(this, e);
if (e.Cancel)
_saveOperationCanceled = true;
}
}
private void OnSaveCompleted()
{
EventHandler<SaveProgressEventArgs> sp = SaveProgress;
if (sp != null)
{
var e = SaveProgressEventArgs.Completed(ArchiveNameForEvent);
sp(this, e);
}
}
#endregion
#region Read
/// <summary>
/// An event handler invoked before, during, and after the reading of a zip archive.
/// </summary>
///
/// <remarks>
/// <para>
/// Depending on the particular event being signaled, different properties on the
/// <see cref="ReadProgressEventArgs"/> parameter are set. The following table
/// summarizes the available EventTypes and the conditions under which this
/// event handler is invoked with a <c>ReadProgressEventArgs</c> with the given EventType.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>value of EntryType</term>
/// <description>Meaning and conditions</description>
/// </listheader>
///
/// <item>
/// <term>ZipProgressEventType.Reading_Started</term>
/// <description>Fired just as ZipFile.Read() begins. Meaningful properties: ArchiveName.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Reading_Completed</term>
/// <description>Fired when ZipFile.Read() has completed. Meaningful properties: ArchiveName.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Reading_ArchiveBytesRead</term>
/// <description>Fired while reading, updates the number of bytes read for the entire archive.
/// Meaningful properties: ArchiveName, CurrentEntry, BytesTransferred, TotalBytesToTransfer.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Reading_BeforeReadEntry</term>
/// <description>Indicates an entry is about to be read from the archive.
/// Meaningful properties: ArchiveName, EntriesTotal.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Reading_AfterReadEntry</term>
/// <description>Indicates an entry has just been read from the archive.
/// Meaningful properties: ArchiveName, EntriesTotal, CurrentEntry.
/// </description>
/// </item>
///
/// </list>
/// </remarks>
///
/// <seealso cref="Ionic.Zip.ZipFile.SaveProgress"/>
/// <seealso cref="Ionic.Zip.ZipFile.AddProgress"/>
/// <seealso cref="Ionic.Zip.ZipFile.ExtractProgress"/>
public event EventHandler<ReadProgressEventArgs> ReadProgress;
private void OnReadStarted()
{
EventHandler<ReadProgressEventArgs> rp = ReadProgress;
if (rp != null)
{
var e = ReadProgressEventArgs.Started(ArchiveNameForEvent);
rp(this, e);
}
}
private void OnReadCompleted()
{
EventHandler<ReadProgressEventArgs> rp = ReadProgress;
if (rp != null)
{
var e = ReadProgressEventArgs.Completed(ArchiveNameForEvent);
rp(this, e);
}
}
internal void OnReadBytes(ZipEntry entry)
{
EventHandler<ReadProgressEventArgs> rp = ReadProgress;
if (rp != null)
{
var e = ReadProgressEventArgs.ByteUpdate(ArchiveNameForEvent,
entry,
ReadStream.Position,
LengthOfReadStream);
rp(this, e);
}
}
internal void OnReadEntry(bool before, ZipEntry entry)
{
EventHandler<ReadProgressEventArgs> rp = ReadProgress;
if (rp != null)
{
ReadProgressEventArgs e = (before)
? ReadProgressEventArgs.Before(ArchiveNameForEvent, _entries.Count)
: ReadProgressEventArgs.After(ArchiveNameForEvent, entry, _entries.Count);
rp(this, e);
}
}
private Int64 _lengthOfReadStream = -99;
private Int64 LengthOfReadStream
{
get
{
if (_lengthOfReadStream == -99)
{
_lengthOfReadStream = (_ReadStreamIsOurs)
? SharedUtilities.GetFileLength(_name)
: -1L;
}
return _lengthOfReadStream;
}
}
#endregion
#region Extract
/// <summary>
/// An event handler invoked before, during, and after extraction of
/// entries in the zip archive.
/// </summary>
///
/// <remarks>
/// <para>
/// Depending on the particular event, different properties on the <see
/// cref="ExtractProgressEventArgs"/> parameter are set. The following
/// table summarizes the available EventTypes and the conditions under
/// which this event handler is invoked with a
/// <c>ExtractProgressEventArgs</c> with the given EventType.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>value of EntryType</term>
/// <description>Meaning and conditions</description>
/// </listheader>
///
/// <item>
/// <term>ZipProgressEventType.Extracting_BeforeExtractAll</term>
/// <description>
/// Set when ExtractAll() begins. The ArchiveName, Overwrite, and
/// ExtractLocation properties are meaningful.</description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Extracting_AfterExtractAll</term>
/// <description>
/// Set when ExtractAll() has completed. The ArchiveName, Overwrite,
/// and ExtractLocation properties are meaningful.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Extracting_BeforeExtractEntry</term>
/// <description>
/// Set when an Extract() on an entry in the ZipFile has begun.
/// Properties that are meaningful: ArchiveName, EntriesTotal,
/// CurrentEntry, Overwrite, ExtractLocation, EntriesExtracted.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Extracting_AfterExtractEntry</term>
/// <description>
/// Set when an Extract() on an entry in the ZipFile has completed.
/// Properties that are meaningful: ArchiveName, EntriesTotal,
/// CurrentEntry, Overwrite, ExtractLocation, EntriesExtracted.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Extracting_EntryBytesWritten</term>
/// <description>
/// Set within a call to Extract() on an entry in the ZipFile, as data
/// is extracted for the entry. Properties that are meaningful:
/// ArchiveName, CurrentEntry, BytesTransferred, TotalBytesToTransfer.
/// </description>
/// </item>
///
/// <item>
/// <term>ZipProgressEventType.Extracting_ExtractEntryWouldOverwrite</term>
/// <description>
/// Set within a call to Extract() on an entry in the ZipFile, when the
/// extraction would overwrite an existing file. This event type is used
/// only when <c>ExtractExistingFileAction</c> on the <c>ZipFile</c> or
/// <c>ZipEntry</c> is set to <c>InvokeExtractProgressEvent</c>.
/// </description>
/// </item>
///
/// </list>
///
/// </remarks>
///
/// <example>
/// <code>
/// private static bool justHadByteUpdate = false;
/// public static void ExtractProgress(object sender, ExtractProgressEventArgs e)
/// {
/// if(e.EventType == ZipProgressEventType.Extracting_EntryBytesWritten)
/// {
/// if (justHadByteUpdate)
/// Console.SetCursorPosition(0, Console.CursorTop);
///
/// Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, e.TotalBytesToTransfer,
/// e.BytesTransferred / (0.01 * e.TotalBytesToTransfer ));
/// justHadByteUpdate = true;
/// }
/// else if(e.EventType == ZipProgressEventType.Extracting_BeforeExtractEntry)
/// {
/// if (justHadByteUpdate)
/// Console.WriteLine();
/// Console.WriteLine("Extracting: {0}", e.CurrentEntry.FileName);
/// justHadByteUpdate= false;
/// }
/// }
///
/// public static ExtractZip(string zipToExtract, string directory)
/// {
/// string TargetDirectory= "extract";
/// using (var zip = ZipFile.Read(zipToExtract)) {
/// zip.ExtractProgress += ExtractProgress;
/// foreach (var e in zip1)
/// {
/// e.Extract(TargetDirectory, true);
/// }
/// }
/// }
///
/// </code>
/// <code lang="VB">
/// Public Shared Sub Main(ByVal args As String())
/// Dim ZipToUnpack As String = "C1P3SML.zip"
/// Dim TargetDir As String = "ExtractTest_Extract"
/// Console.WriteLine("Extracting file {0} to {1}", ZipToUnpack, TargetDir)
/// Using zip1 As ZipFile = ZipFile.Read(ZipToUnpack)
/// AddHandler zip1.ExtractProgress, AddressOf MyExtractProgress
/// Dim e As ZipEntry
/// For Each e In zip1
/// e.Extract(TargetDir, True)
/// Next
/// End Using
/// End Sub
///
/// Private Shared justHadByteUpdate As Boolean = False
///
/// Public Shared Sub MyExtractProgress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
/// If (e.EventType = ZipProgressEventType.Extracting_EntryBytesWritten) Then
/// If ExtractTest.justHadByteUpdate Then
/// Console.SetCursorPosition(0, Console.CursorTop)
/// End If
/// Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, e.TotalBytesToTransfer, (CDbl(e.BytesTransferred) / (0.01 * e.TotalBytesToTransfer)))
/// ExtractTest.justHadByteUpdate = True
/// ElseIf (e.EventType = ZipProgressEventType.Extracting_BeforeExtractEntry) Then
/// If ExtractTest.justHadByteUpdate Then
/// Console.WriteLine
/// End If
/// Console.WriteLine("Extracting: {0}", e.CurrentEntry.FileName)
/// ExtractTest.justHadByteUpdate = False
/// End If
/// End Sub
/// </code>
/// </example>
///
/// <seealso cref="Ionic.Zip.ZipFile.SaveProgress"/>
/// <seealso cref="Ionic.Zip.ZipFile.ReadProgress"/>
/// <seealso cref="Ionic.Zip.ZipFile.AddProgress"/>
public event EventHandler<ExtractProgressEventArgs> ExtractProgress;
private void OnExtractEntry(int current, bool before, ZipEntry currentEntry, string path)
{
EventHandler<ExtractProgressEventArgs> ep = ExtractProgress;
if (ep != null)
{
var e = new ExtractProgressEventArgs(ArchiveNameForEvent, before, _entries.Count, current, currentEntry, path);
ep(this, e);
if (e.Cancel)
_extractOperationCanceled = true;
}
}
// Can be called from within ZipEntry._ExtractOne.
internal bool OnExtractBlock(ZipEntry entry, Int64 bytesWritten, Int64 totalBytesToWrite)
{
EventHandler<ExtractProgressEventArgs> ep = ExtractProgress;
if (ep != null)
{
var e = ExtractProgressEventArgs.ByteUpdate(ArchiveNameForEvent, entry,
bytesWritten, totalBytesToWrite);
ep(this, e);
if (e.Cancel)
_extractOperationCanceled = true;
}
return _extractOperationCanceled;
}
// Can be called from within ZipEntry.InternalExtract.
internal bool OnSingleEntryExtract(ZipEntry entry, string path, bool before)
{
EventHandler<ExtractProgressEventArgs> ep = ExtractProgress;
if (ep != null)
{
var e = (before)
? ExtractProgressEventArgs.BeforeExtractEntry(ArchiveNameForEvent, entry, path)
: ExtractProgressEventArgs.AfterExtractEntry(ArchiveNameForEvent, entry, path);
ep(this, e);
if (e.Cancel)
_extractOperationCanceled = true;
}
return _extractOperationCanceled;
}
internal bool OnExtractExisting(ZipEntry entry, string path)
{
EventHandler<ExtractProgressEventArgs> ep = ExtractProgress;
if (ep != null)
{
var e = ExtractProgressEventArgs.ExtractExisting(ArchiveNameForEvent, entry, path);
ep(this, e);
if (e.Cancel)
_extractOperationCanceled = true;
}
return _extractOperationCanceled;
}
private void OnExtractAllCompleted(string path)
{
EventHandler<ExtractProgressEventArgs> ep = ExtractProgress;
if (ep != null)
{
var e = ExtractProgressEventArgs.ExtractAllCompleted(ArchiveNameForEvent,
path );
ep(this, e);
}
}
private void OnExtractAllStarted(string path)
{
EventHandler<ExtractProgressEventArgs> ep = ExtractProgress;
if (ep != null)
{
var e = ExtractProgressEventArgs.ExtractAllStarted(ArchiveNameForEvent,
path );
ep(this, e);
}
}
#endregion
#region Add
/// <summary>
/// An event handler invoked before, during, and after Adding entries to a zip archive.
/// </summary>
///
/// <remarks>
/// Adding a large number of entries to a zip file can take a long
/// time. For example, when calling <see cref="AddDirectory(string)"/> on a
/// directory that contains 50,000 files, it could take 3 minutes or so.
/// This event handler allws an application to track the progress of the Add
/// operation, and to optionally cancel a lengthy Add operation.
/// </remarks>
///
/// <example>
/// <code lang="C#">
///
/// int _numEntriesToAdd= 0;
/// int _numEntriesAdded= 0;
/// void AddProgressHandler(object sender, AddProgressEventArgs e)
/// {
/// switch (e.EventType)
/// {
/// case ZipProgressEventType.Adding_Started:
/// Console.WriteLine("Adding files to the zip...");
/// break;
/// case ZipProgressEventType.Adding_AfterAddEntry:
/// _numEntriesAdded++;
/// Console.WriteLine(String.Format("Adding file {0}/{1} :: {2}",
/// _numEntriesAdded, _numEntriesToAdd, e.CurrentEntry.FileName));
/// break;
/// case ZipProgressEventType.Adding_Completed:
/// Console.WriteLine("Added all files");
/// break;
/// }
/// }
///
/// void CreateTheZip()
/// {
/// using (ZipFile zip = new ZipFile())
/// {
/// zip.AddProgress += AddProgressHandler;
/// zip.AddDirectory(System.IO.Path.GetFileName(DirToZip));
/// zip.Save(ZipFileToCreate);
/// }
/// }
///
/// </code>
///
/// <code lang="VB">
///
/// Private Sub AddProgressHandler(ByVal sender As Object, ByVal e As AddProgressEventArgs)
/// Select Case e.EventType
/// Case ZipProgressEventType.Adding_Started
/// Console.WriteLine("Adding files to the zip...")
/// Exit Select
/// Case ZipProgressEventType.Adding_AfterAddEntry