-
Notifications
You must be signed in to change notification settings - Fork 979
/
Copy pathZipFile.cs
4933 lines (4217 loc) · 133 KB
/
ZipFile.cs
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
using ICSharpCode.SharpZipLib.Checksum;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Encryption;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace ICSharpCode.SharpZipLib.Zip
{
#region Keys Required Event Args
/// <summary>
/// Arguments used with KeysRequiredEvent
/// </summary>
public class KeysRequiredEventArgs : EventArgs
{
#region Constructors
/// <summary>
/// Initialise a new instance of <see cref="KeysRequiredEventArgs"></see>
/// </summary>
/// <param name="name">The name of the file for which keys are required.</param>
public KeysRequiredEventArgs(string name)
{
fileName = name;
}
/// <summary>
/// Initialise a new instance of <see cref="KeysRequiredEventArgs"></see>
/// </summary>
/// <param name="name">The name of the file for which keys are required.</param>
/// <param name="keyValue">The current key value.</param>
public KeysRequiredEventArgs(string name, byte[] keyValue)
{
fileName = name;
key = keyValue;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets the name of the file for which keys are required.
/// </summary>
public string FileName
{
get { return fileName; }
}
/// <summary>
/// Gets or sets the key value
/// </summary>
public byte[] Key
{
get { return key; }
set { key = value; }
}
#endregion Properties
#region Instance Fields
private readonly string fileName;
private byte[] key;
#endregion Instance Fields
}
#endregion Keys Required Event Args
#region Test Definitions
/// <summary>
/// The strategy to apply to testing.
/// </summary>
public enum TestStrategy
{
/// <summary>
/// Find the first error only.
/// </summary>
FindFirstError,
/// <summary>
/// Find all possible errors.
/// </summary>
FindAllErrors,
}
/// <summary>
/// The operation in progress reported by a <see cref="ZipTestResultHandler"/> during testing.
/// </summary>
/// <seealso cref="ZipFile.TestArchive(bool)">TestArchive</seealso>
public enum TestOperation
{
/// <summary>
/// Setting up testing.
/// </summary>
Initialising,
/// <summary>
/// Testing an individual entries header
/// </summary>
EntryHeader,
/// <summary>
/// Testing an individual entries data
/// </summary>
EntryData,
/// <summary>
/// Testing an individual entry has completed.
/// </summary>
EntryComplete,
/// <summary>
/// Running miscellaneous tests
/// </summary>
MiscellaneousTests,
/// <summary>
/// Testing is complete
/// </summary>
Complete,
}
/// <summary>
/// Status returned by <see cref="ZipTestResultHandler"/> during testing.
/// </summary>
/// <seealso cref="ZipFile.TestArchive(bool)">TestArchive</seealso>
public class TestStatus
{
#region Constructors
/// <summary>
/// Initialise a new instance of <see cref="TestStatus"/>
/// </summary>
/// <param name="file">The <see cref="ZipFile"/> this status applies to.</param>
public TestStatus(ZipFile file)
{
file_ = file;
}
#endregion Constructors
#region Properties
/// <summary>
/// Get the current <see cref="TestOperation"/> in progress.
/// </summary>
public TestOperation Operation
{
get { return operation_; }
}
/// <summary>
/// Get the <see cref="ZipFile"/> this status is applicable to.
/// </summary>
public ZipFile File
{
get { return file_; }
}
/// <summary>
/// Get the current/last entry tested.
/// </summary>
public ZipEntry Entry
{
get { return entry_; }
}
/// <summary>
/// Get the number of errors detected so far.
/// </summary>
public int ErrorCount
{
get { return errorCount_; }
}
/// <summary>
/// Get the number of bytes tested so far for the current entry.
/// </summary>
public long BytesTested
{
get { return bytesTested_; }
}
/// <summary>
/// Get a value indicating whether the last entry test was valid.
/// </summary>
public bool EntryValid
{
get { return entryValid_; }
}
#endregion Properties
#region Internal API
internal void AddError()
{
errorCount_++;
entryValid_ = false;
}
internal void SetOperation(TestOperation operation)
{
operation_ = operation;
}
internal void SetEntry(ZipEntry entry)
{
entry_ = entry;
entryValid_ = true;
bytesTested_ = 0;
}
internal void SetBytesTested(long value)
{
bytesTested_ = value;
}
#endregion Internal API
#region Instance Fields
private readonly ZipFile file_;
private ZipEntry entry_;
private bool entryValid_;
private int errorCount_;
private long bytesTested_;
private TestOperation operation_;
#endregion Instance Fields
}
/// <summary>
/// Delegate invoked during <see cref="ZipFile.TestArchive(bool, TestStrategy, ZipTestResultHandler)">testing</see> if supplied indicating current progress and status.
/// </summary>
/// <remarks>If the message is non-null an error has occured. If the message is null
/// the operation as found in <see cref="TestStatus">status</see> has started.</remarks>
public delegate void ZipTestResultHandler(TestStatus status, string message);
#endregion Test Definitions
#region Update Definitions
/// <summary>
/// The possible ways of <see cref="ZipFile.CommitUpdate()">applying updates</see> to an archive.
/// </summary>
public enum FileUpdateMode
{
/// <summary>
/// Perform all updates on temporary files ensuring that the original file is saved.
/// </summary>
Safe,
/// <summary>
/// Update the archive directly, which is faster but less safe.
/// </summary>
Direct,
}
#endregion Update Definitions
#region ZipFile Class
/// <summary>
/// This class represents a Zip archive. You can ask for the contained
/// entries, or get an input stream for a file entry. The entry is
/// automatically decompressed.
///
/// You can also update the archive adding or deleting entries.
///
/// This class is thread safe for input: You can open input streams for arbitrary
/// entries in different threads.
/// <br/>
/// <br/>Author of the original java version : Jochen Hoenicke
/// </summary>
/// <example>
/// <code>
/// using System;
/// using System.Text;
/// using System.Collections;
/// using System.IO;
///
/// using ICSharpCode.SharpZipLib.Zip;
///
/// class MainClass
/// {
/// static public void Main(string[] args)
/// {
/// using (ZipFile zFile = new ZipFile(args[0])) {
/// Console.WriteLine("Listing of : " + zFile.Name);
/// Console.WriteLine("");
/// Console.WriteLine("Raw Size Size Date Time Name");
/// Console.WriteLine("-------- -------- -------- ------ ---------");
/// foreach (ZipEntry e in zFile) {
/// if ( e.IsFile ) {
/// DateTime d = e.DateTime;
/// Console.WriteLine("{0, -10}{1, -10}{2} {3} {4}", e.Size, e.CompressedSize,
/// d.ToString("dd-MM-yy"), d.ToString("HH:mm"),
/// e.Name);
/// }
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public class ZipFile : IEnumerable, IDisposable
{
#region KeyHandling
/// <summary>
/// Delegate for handling keys/password setting during compression/decompression.
/// </summary>
public delegate void KeysRequiredEventHandler(
object sender,
KeysRequiredEventArgs e
);
/// <summary>
/// Event handler for handling encryption keys.
/// </summary>
public KeysRequiredEventHandler KeysRequired;
/// <summary>
/// Handles getting of encryption keys when required.
/// </summary>
/// <param name="fileName">The file for which encryption keys are required.</param>
private void OnKeysRequired(string fileName)
{
if (KeysRequired != null)
{
var krea = new KeysRequiredEventArgs(fileName, key);
KeysRequired(this, krea);
key = krea.Key;
}
}
/// <summary>
/// Get/set the encryption key value.
/// </summary>
private byte[] Key
{
get { return key; }
set { key = value; }
}
/// <summary>
/// Password to be used for encrypting/decrypting files.
/// </summary>
/// <remarks>Set to null if no password is required.</remarks>
public string Password
{
set
{
if (string.IsNullOrEmpty(value))
{
key = null;
}
else
{
key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(value));
}
rawPassword_ = value;
}
}
/// <summary>
/// Get a value indicating whether encryption keys are currently available.
/// </summary>
private bool HaveKeys
{
get { return key != null; }
}
#endregion KeyHandling
#region Constructors
/// <summary>
/// Opens a Zip file with the given name for reading.
/// </summary>
/// <param name="name">The name of the file to open.</param>
/// <exception cref="ArgumentNullException">The argument supplied is null.</exception>
/// <exception cref="IOException">
/// An i/o error occurs
/// </exception>
/// <exception cref="ZipException">
/// The file doesn't contain a valid zip archive.
/// </exception>
public ZipFile(string name)
{
name_ = name ?? throw new ArgumentNullException(nameof(name));
baseStream_ = File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read);
isStreamOwner = true;
try
{
ReadEntries();
}
catch
{
DisposeInternal(true);
throw;
}
}
/// <summary>
/// Opens a Zip file reading the given <see cref="FileStream"/>.
/// </summary>
/// <param name="file">The <see cref="FileStream"/> to read archive data from.</param>
/// <exception cref="ArgumentNullException">The supplied argument is null.</exception>
/// <exception cref="IOException">
/// An i/o error occurs.
/// </exception>
/// <exception cref="ZipException">
/// The file doesn't contain a valid zip archive.
/// </exception>
public ZipFile(FileStream file) :
this(file, false)
{
}
/// <summary>
/// Opens a Zip file reading the given <see cref="FileStream"/>.
/// </summary>
/// <param name="file">The <see cref="FileStream"/> to read archive data from.</param>
/// <param name="leaveOpen">true to leave the <see cref="FileStream">file</see> open when the ZipFile is disposed, false to dispose of it</param>
/// <exception cref="ArgumentNullException">The supplied argument is null.</exception>
/// <exception cref="IOException">
/// An i/o error occurs.
/// </exception>
/// <exception cref="ZipException">
/// The file doesn't contain a valid zip archive.
/// </exception>
public ZipFile(FileStream file, bool leaveOpen)
{
if (file == null)
{
throw new ArgumentNullException(nameof(file));
}
if (!file.CanSeek)
{
throw new ArgumentException("Stream is not seekable", nameof(file));
}
baseStream_ = file;
name_ = file.Name;
isStreamOwner = !leaveOpen;
try
{
ReadEntries();
}
catch
{
DisposeInternal(true);
throw;
}
}
/// <summary>
/// Opens a Zip file reading the given <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> to read archive data from.</param>
/// <exception cref="IOException">
/// An i/o error occurs
/// </exception>
/// <exception cref="ZipException">
/// The stream doesn't contain a valid zip archive.<br/>
/// </exception>
/// <exception cref="ArgumentException">
/// The <see cref="Stream">stream</see> doesnt support seeking.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The <see cref="Stream">stream</see> argument is null.
/// </exception>
public ZipFile(Stream stream) :
this(stream, false)
{
}
/// <summary>
/// Opens a Zip file reading the given <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> to read archive data from.</param>
/// <param name="leaveOpen">true to leave the <see cref="Stream">stream</see> open when the ZipFile is disposed, false to dispose of it</param>
/// <exception cref="IOException">
/// An i/o error occurs
/// </exception>
/// <exception cref="ZipException">
/// The stream doesn't contain a valid zip archive.<br/>
/// </exception>
/// <exception cref="ArgumentException">
/// The <see cref="Stream">stream</see> doesnt support seeking.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The <see cref="Stream">stream</see> argument is null.
/// </exception>
public ZipFile(Stream stream, bool leaveOpen)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanSeek)
{
throw new ArgumentException("Stream is not seekable", nameof(stream));
}
baseStream_ = stream;
isStreamOwner = !leaveOpen;
if (baseStream_.Length > 0)
{
try
{
ReadEntries();
}
catch
{
DisposeInternal(true);
throw;
}
}
else
{
entries_ = new ZipEntry[0];
isNewArchive_ = true;
}
}
/// <summary>
/// Initialises a default <see cref="ZipFile"/> instance with no entries and no file storage.
/// </summary>
internal ZipFile()
{
entries_ = new ZipEntry[0];
isNewArchive_ = true;
}
#endregion Constructors
#region Destructors and Closing
/// <summary>
/// Finalize this instance.
/// </summary>
~ZipFile()
{
Dispose(false);
}
/// <summary>
/// Closes the ZipFile. If the stream is <see cref="IsStreamOwner">owned</see> then this also closes the underlying input stream.
/// Once closed, no further instance methods should be called.
/// </summary>
/// <exception cref="System.IO.IOException">
/// An i/o error occurs.
/// </exception>
public void Close()
{
DisposeInternal(true);
GC.SuppressFinalize(this);
}
#endregion Destructors and Closing
#region Creators
/// <summary>
/// Create a new <see cref="ZipFile"/> whose data will be stored in a file.
/// </summary>
/// <param name="fileName">The name of the archive to create.</param>
/// <returns>Returns the newly created <see cref="ZipFile"/></returns>
/// <exception cref="ArgumentNullException"><paramref name="fileName"></paramref> is null</exception>
public static ZipFile Create(string fileName)
{
if (fileName == null)
{
throw new ArgumentNullException(nameof(fileName));
}
FileStream fs = File.Create(fileName);
return new ZipFile
{
name_ = fileName,
baseStream_ = fs,
isStreamOwner = true
};
}
/// <summary>
/// Create a new <see cref="ZipFile"/> whose data will be stored on a stream.
/// </summary>
/// <param name="outStream">The stream providing data storage.</param>
/// <returns>Returns the newly created <see cref="ZipFile"/></returns>
/// <exception cref="ArgumentNullException"><paramref name="outStream"> is null</paramref></exception>
/// <exception cref="ArgumentException"><paramref name="outStream"> doesnt support writing.</paramref></exception>
public static ZipFile Create(Stream outStream)
{
if (outStream == null)
{
throw new ArgumentNullException(nameof(outStream));
}
if (!outStream.CanWrite)
{
throw new ArgumentException("Stream is not writeable", nameof(outStream));
}
if (!outStream.CanSeek)
{
throw new ArgumentException("Stream is not seekable", nameof(outStream));
}
var result = new ZipFile
{
baseStream_ = outStream
};
return result;
}
#endregion Creators
#region Properties
/// <summary>
/// Get/set a flag indicating if the underlying stream is owned by the ZipFile instance.
/// If the flag is true then the stream will be closed when <see cref="Close">Close</see> is called.
/// </summary>
/// <remarks>
/// The default value is true in all cases.
/// </remarks>
public bool IsStreamOwner
{
get { return isStreamOwner; }
set { isStreamOwner = value; }
}
/// <summary>
/// Get a value indicating whether
/// this archive is embedded in another file or not.
/// </summary>
public bool IsEmbeddedArchive
{
// Not strictly correct in all circumstances currently
get { return offsetOfFirstEntry > 0; }
}
/// <summary>
/// Get a value indicating that this archive is a new one.
/// </summary>
public bool IsNewArchive
{
get { return isNewArchive_; }
}
/// <summary>
/// Gets the comment for the zip file.
/// </summary>
public string ZipFileComment
{
get { return comment_; }
}
/// <summary>
/// Gets the name of this zip file.
/// </summary>
public string Name
{
get { return name_; }
}
/// <summary>
/// Gets the number of entries in this zip file.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The Zip file has been closed.
/// </exception>
[Obsolete("Use the Count property instead")]
public int Size
{
get
{
return entries_.Length;
}
}
/// <summary>
/// Get the number of entries contained in this <see cref="ZipFile"/>.
/// </summary>
public long Count
{
get
{
return entries_.Length;
}
}
/// <summary>
/// Indexer property for ZipEntries
/// </summary>
[System.Runtime.CompilerServices.IndexerNameAttribute("EntryByIndex")]
public ZipEntry this[int index]
{
get
{
return (ZipEntry)entries_[index].Clone();
}
}
#endregion Properties
#region Input Handling
/// <summary>
/// Gets an enumerator for the Zip entries in this Zip file.
/// </summary>
/// <returns>Returns an <see cref="IEnumerator"/> for this archive.</returns>
/// <exception cref="ObjectDisposedException">
/// The Zip file has been closed.
/// </exception>
public IEnumerator GetEnumerator()
{
if (isDisposed_)
{
throw new ObjectDisposedException("ZipFile");
}
return new ZipEntryEnumerator(entries_);
}
/// <summary>
/// Return the index of the entry with a matching name
/// </summary>
/// <param name="name">Entry name to find</param>
/// <param name="ignoreCase">If true the comparison is case insensitive</param>
/// <returns>The index position of the matching entry or -1 if not found</returns>
/// <exception cref="ObjectDisposedException">
/// The Zip file has been closed.
/// </exception>
public int FindEntry(string name, bool ignoreCase)
{
if (isDisposed_)
{
throw new ObjectDisposedException("ZipFile");
}
// TODO: This will be slow as the next ice age for huge archives!
for (int i = 0; i < entries_.Length; i++)
{
if (string.Compare(name, entries_[i].Name, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0)
{
return i;
}
}
return -1;
}
/// <summary>
/// Searches for a zip entry in this archive with the given name.
/// String comparisons are case insensitive
/// </summary>
/// <param name="name">
/// The name to find. May contain directory components separated by slashes ('/').
/// </param>
/// <returns>
/// A clone of the zip entry, or null if no entry with that name exists.
/// </returns>
/// <exception cref="ObjectDisposedException">
/// The Zip file has been closed.
/// </exception>
public ZipEntry GetEntry(string name)
{
if (isDisposed_)
{
throw new ObjectDisposedException("ZipFile");
}
int index = FindEntry(name, true);
return (index >= 0) ? (ZipEntry)entries_[index].Clone() : null;
}
/// <summary>
/// Gets an input stream for reading the given zip entry data in an uncompressed form.
/// Normally the <see cref="ZipEntry"/> should be an entry returned by GetEntry().
/// </summary>
/// <param name="entry">The <see cref="ZipEntry"/> to obtain a data <see cref="Stream"/> for</param>
/// <returns>An input <see cref="Stream"/> containing data for this <see cref="ZipEntry"/></returns>
/// <exception cref="ObjectDisposedException">
/// The ZipFile has already been closed
/// </exception>
/// <exception cref="ICSharpCode.SharpZipLib.Zip.ZipException">
/// The compression method for the entry is unknown
/// </exception>
/// <exception cref="IndexOutOfRangeException">
/// The entry is not found in the ZipFile
/// </exception>
public Stream GetInputStream(ZipEntry entry)
{
if (entry == null)
{
throw new ArgumentNullException(nameof(entry));
}
if (isDisposed_)
{
throw new ObjectDisposedException("ZipFile");
}
long index = entry.ZipFileIndex;
if ((index < 0) || (index >= entries_.Length) || (entries_[index].Name != entry.Name))
{
index = FindEntry(entry.Name, true);
if (index < 0)
{
throw new ZipException("Entry cannot be found");
}
}
return GetInputStream(index);
}
/// <summary>
/// Creates an input stream reading a zip entry
/// </summary>
/// <param name="entryIndex">The index of the entry to obtain an input stream for.</param>
/// <returns>
/// An input <see cref="Stream"/> containing data for this <paramref name="entryIndex"/>
/// </returns>
/// <exception cref="ObjectDisposedException">
/// The ZipFile has already been closed
/// </exception>
/// <exception cref="ICSharpCode.SharpZipLib.Zip.ZipException">
/// The compression method for the entry is unknown
/// </exception>
/// <exception cref="IndexOutOfRangeException">
/// The entry is not found in the ZipFile
/// </exception>
public Stream GetInputStream(long entryIndex)
{
if (isDisposed_)
{
throw new ObjectDisposedException("ZipFile");
}
long start = LocateEntry(entries_[entryIndex]);
CompressionMethod method = entries_[entryIndex].CompressionMethod;
Stream result = new PartialInputStream(this, start, entries_[entryIndex].CompressedSize);
if (entries_[entryIndex].IsCrypted == true)
{
result = CreateAndInitDecryptionStream(result, entries_[entryIndex]);
if (result == null)
{
throw new ZipException("Unable to decrypt this entry");
}
}
switch (method)
{
case CompressionMethod.Stored:
// read as is.
break;
case CompressionMethod.Deflated:
// No need to worry about ownership and closing as underlying stream close does nothing.
result = new InflaterInputStream(result, new Inflater(true));
break;
case CompressionMethod.BZip2:
result = new BZip2.BZip2InputStream(result);
break;
default:
throw new ZipException("Unsupported compression method " + method);
}
return result;
}
#endregion Input Handling
#region Archive Testing
/// <summary>
/// Test an archive for integrity/validity
/// </summary>
/// <param name="testData">Perform low level data Crc check</param>
/// <returns>true if all tests pass, false otherwise</returns>
/// <remarks>Testing will terminate on the first error found.</remarks>
public bool TestArchive(bool testData)
{
return TestArchive(testData, TestStrategy.FindFirstError, null);
}
/// <summary>
/// Test an archive for integrity/validity
/// </summary>
/// <param name="testData">Perform low level data Crc check</param>
/// <param name="strategy">The <see cref="TestStrategy"></see> to apply.</param>
/// <param name="resultHandler">The <see cref="ZipTestResultHandler"></see> handler to call during testing.</param>
/// <returns>true if all tests pass, false otherwise</returns>
/// <exception cref="ObjectDisposedException">The object has already been closed.</exception>
public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandler resultHandler)
{
if (isDisposed_)
{
throw new ObjectDisposedException("ZipFile");
}
var status = new TestStatus(this);
resultHandler?.Invoke(status, null);
HeaderTest test = testData ? (HeaderTest.Header | HeaderTest.Extract) : HeaderTest.Header;
bool testing = true;
try
{
int entryIndex = 0;
while (testing && (entryIndex < Count))
{
if (resultHandler != null)
{
status.SetEntry(this[entryIndex]);
status.SetOperation(TestOperation.EntryHeader);
resultHandler(status, null);
}
try
{
TestLocalHeader(this[entryIndex], test);
}
catch (ZipException ex)
{
status.AddError();
resultHandler?.Invoke(status, $"Exception during test - '{ex.Message}'");
testing &= strategy != TestStrategy.FindFirstError;
}
if (testing && testData && this[entryIndex].IsFile)
{
if (resultHandler != null)
{
status.SetOperation(TestOperation.EntryData);
resultHandler(status, null);
}
var crc = new Crc32();
using (Stream entryStream = this.GetInputStream(this[entryIndex]))
{
byte[] buffer = new byte[4096];
long totalBytes = 0;
int bytesRead;
while ((bytesRead = entryStream.Read(buffer, 0, buffer.Length)) > 0)
{
crc.Update(new ArraySegment<byte>(buffer, 0, bytesRead));
if (resultHandler != null)
{
totalBytes += bytesRead;
status.SetBytesTested(totalBytes);
resultHandler(status, null);
}
}
}
if (this[entryIndex].Crc != crc.Value)
{
status.AddError();
resultHandler?.Invoke(status, "CRC mismatch");
testing &= strategy != TestStrategy.FindFirstError;
}
if ((this[entryIndex].Flags & (int)GeneralBitFlags.Descriptor) != 0)
{
var helper = new ZipHelperStream(baseStream_);