root/trunk/Updater/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @ 597

Wersja 597, 23.4 KB (wprowadzona przez marek, 17 years temu)

re #165

Line 
1// ZipOutputStream.cs
2//
3// Copyright (C) 2001 Mike Krueger
4// Copyright (C) 2004 John Reilly
5//
6// This file was translated from java, it was part of the GNU Classpath
7// Copyright (C) 2001 Free Software Foundation, Inc.
8//
9// This program is free software; you can redistribute it and/or
10// modify it under the terms of the GNU General Public License
11// as published by the Free Software Foundation; either version 2
12// of the License, or (at your option) any later version.
13//
14// This program is distributed in the hope that it will be useful,
15// but WITHOUT ANY WARRANTY; without even the implied warranty of
16// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17// GNU General Public License for more details.
18//
19// You should have received a copy of the GNU General Public License
20// along with this program; if not, write to the Free Software
21// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22//
23// Linking this library statically or dynamically with other modules is
24// making a combined work based on this library.  Thus, the terms and
25// conditions of the GNU General Public License cover the whole
26// combination.
27//
28// As a special exception, the copyright holders of this library give you
29// permission to link this library with independent modules to produce an
30// executable, regardless of the license terms of these independent
31// modules, and to copy and distribute the resulting executable under
32// terms of your choice, provided that you also meet, for each linked
33// independent module, the terms and conditions of the license of that
34// module.  An independent module is a module which is not derived from
35// or based on this library.  If you modify this library, you may extend
36// this exception to your version of the library, but you are not
37// obligated to do so.  If you do not wish to do so, delete this
38// exception statement from your version.
39
40using System;
41using System.IO;
42using System.Collections;
43using System.Text;
44
45using ICSharpCode.SharpZipLib.Checksums;
46using ICSharpCode.SharpZipLib.Zip.Compression;
47using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
48
49namespace ICSharpCode.SharpZipLib.Zip
50{
51        /// <summary>
52        /// This is a DeflaterOutputStream that writes the files into a zip
53        /// archive one after another.  It has a special method to start a new
54        /// zip entry.  The zip entries contains information about the file name
55        /// size, compressed size, CRC, etc.
56        ///
57        /// It includes support for Stored and Deflated entries.
58        /// This class is not thread safe.
59        /// <br/>
60        /// <br/>Author of the original java version : Jochen Hoenicke
61        /// </summary>
62        /// <example> This sample shows how to create a zip file
63        /// <code>
64        /// using System;
65        /// using System.IO;
66        ///
67        /// using ICSharpCode.SharpZipLib.Core;
68        /// using ICSharpCode.SharpZipLib.Zip;
69        ///
70        /// class MainClass
71        /// {
72        ///     public static void Main(string[] args)
73        ///     {
74        ///             string[] filenames = Directory.GetFiles(args[0]);
75        ///             byte[] buffer = new byte[4096];
76        ///             
77        ///             using ( ZipOutputStream s = new ZipOutputStream(File.Create(args[1])) ) {
78        ///             
79        ///                     s.SetLevel(9); // 0 - store only to 9 - means best compression
80        ///             
81        ///                     foreach (string file in filenames) {
82        ///                             ZipEntry entry = new ZipEntry(file);
83        ///                             s.PutNextEntry(entry);
84        ///
85        ///                             using (FileStream fs = File.OpenRead(file)) {
86        ///                                             StreamUtils.Copy(fs, s, buffer);
87        ///                             }
88        ///                     }
89        ///             }
90        ///     }
91        /// }   
92        /// </code>
93        /// </example>
94        public class ZipOutputStream : DeflaterOutputStream
95        {
96                #region Constructors
97                /// <summary>
98                /// Creates a new Zip output stream, writing a zip archive.
99                /// </summary>
100                /// <param name="baseOutputStream">
101                /// The output stream to which the archive contents are written.
102                /// </param>
103                public ZipOutputStream(Stream baseOutputStream)
104                        : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true))
105                {
106                }
107                #endregion
108               
109                /// <summary>
110                /// Gets a flag value of true if the central header has been added for this archive; false if it has not been added.
111                /// </summary>
112                /// <remarks>No further entries can be added once this has been done.</remarks>
113                public bool IsFinished
114                {
115                        get {
116                                return entries == null;
117                        }
118                }
119
120                /// <summary>
121                /// Set the zip file comment.
122                /// </summary>
123                /// <param name="comment">
124                /// The comment text for the entire archive.
125                /// </param>
126                /// <exception name ="ArgumentOutOfRangeException">
127                /// The converted comment is longer than 0xffff bytes.
128                /// </exception>
129                public void SetComment(string comment)
130                {
131                        // TODO: Its not yet clear how to handle unicode comments here.
132                        byte[] commentBytes = ZipConstants.ConvertToArray(comment);
133                        if (commentBytes.Length > 0xffff) {
134                                throw new ArgumentOutOfRangeException("comment");
135                        }
136                        zipComment = commentBytes;
137                }
138               
139                /// <summary>
140                /// Sets the compression level.  The new level will be activated
141                /// immediately.
142                /// </summary>
143                /// <param name="level">The new compression level (1 to 9).</param>
144                /// <exception cref="ArgumentOutOfRangeException">
145                /// Level specified is not supported.
146                /// </exception>
147                /// <see cref="ICSharpCode.SharpZipLib.Zip.Compression.Deflater"/>
148                public void SetLevel(int level)
149                {
150                        deflater_.SetLevel(level);
151                        defaultCompressionLevel = level;
152                }
153               
154                /// <summary>
155                /// Get the current deflater compression level
156                /// </summary>
157                /// <returns>The current compression level</returns>
158                public int GetLevel()
159                {
160                        return deflater_.GetLevel();
161                }
162
163                /// <summary>
164                /// Get / set a value indicating how Zip64 Extension usage is determined when adding entries.
165                /// </summary>
166                /// <remarks>Older archivers may not understand Zip64 extensions.
167                /// If backwards compatability is an issue be careful when adding <see cref="ZipEntry.Size">entries</see> to an archive.
168                /// Setting this property to off is workable but less desirable as in those circumstances adding a file
169                /// larger then 4GB will fail.</remarks>
170                public UseZip64 UseZip64
171                {
172                        get { return useZip64_; }
173                        set { useZip64_ = value; }
174                }
175               
176                /// <summary>
177                /// Write an unsigned short in little endian byte order.
178                /// </summary>
179                private void WriteLeShort(int value)
180                {
181                        unchecked {
182                                baseOutputStream_.WriteByte((byte)(value & 0xff));
183                                baseOutputStream_.WriteByte((byte)((value >> 8) & 0xff));
184                        }
185                }
186               
187                /// <summary>
188                /// Write an int in little endian byte order.
189                /// </summary>
190                private void WriteLeInt(int value)
191                {
192                        unchecked {
193                                WriteLeShort(value);
194                                WriteLeShort(value >> 16);
195                        }
196                }
197               
198                /// <summary>
199                /// Write an int in little endian byte order.
200                /// </summary>
201                private void WriteLeLong(long value)
202                {
203                        unchecked {
204                                WriteLeInt((int)value);
205                                WriteLeInt((int)(value >> 32));
206                        }
207                }
208               
209                /// <summary>
210                /// Starts a new Zip entry. It automatically closes the previous
211                /// entry if present.
212                /// All entry elements bar name are optional, but must be correct if present.
213                /// If the compression method is stored and the output is not patchable
214                /// the compression for that entry is automatically changed to deflate level 0
215                /// </summary>
216                /// <param name="entry">
217                /// the entry.
218                /// </param>
219                /// <exception cref="System.ArgumentNullException">
220                /// if entry passed is null.
221                /// </exception>
222                /// <exception cref="System.IO.IOException">
223                /// if an I/O error occured.
224                /// </exception>
225                /// <exception cref="System.InvalidOperationException">
226                /// if stream was finished
227                /// </exception>
228                /// <exception cref="ZipException">
229                /// Too many entries in the Zip file<br/>
230                /// Entry name is too long<br/>
231                /// Finish has already been called<br/>
232                /// </exception>
233                public void PutNextEntry(ZipEntry entry)
234                {
235                        if ( entry == null ) {
236                                throw new ArgumentNullException("entry");
237                        }
238
239                        if (entries == null) {
240                                throw new InvalidOperationException("ZipOutputStream was finished");
241                        }
242                       
243                        if (curEntry != null) {
244                                CloseEntry();
245                        }
246
247                        if (entries.Count == int.MaxValue) {
248                                throw new ZipException("Too many entries for Zip file");
249                        }
250                       
251                        CompressionMethod method = entry.CompressionMethod;
252                        int compressionLevel = defaultCompressionLevel;
253                       
254                        // Clear flags that the library manages internally
255                        entry.Flags &= (int)GeneralBitFlags.UnicodeText;
256                        patchEntryHeader = false;
257
258                        bool headerInfoAvailable;
259
260                        // No need to compress - definitely no data.
261                        if (entry.Size == 0)
262                        {
263                                entry.CompressedSize = entry.Size;
264                                entry.Crc = 0;
265                                method = CompressionMethod.Stored;
266                                headerInfoAvailable = true;
267                        }
268                        else
269                        {
270                                headerInfoAvailable = (entry.Size >= 0) && entry.HasCrc;
271
272                                // Switch to deflation if storing isnt possible.
273                                if (method == CompressionMethod.Stored)
274                                {
275                                        if (!headerInfoAvailable)
276                                        {
277                                                if (!CanPatchEntries)
278                                                {
279                                                        // Can't patch entries so storing is not possible.
280                                                        method = CompressionMethod.Deflated;
281                                                        compressionLevel = 0;
282                                                }
283                                        }
284                                        else // entry.size must be > 0
285                                        {
286                                                entry.CompressedSize = entry.Size;
287                                                headerInfoAvailable = entry.HasCrc;
288                                        }
289                                }
290                        }
291
292                        if (headerInfoAvailable == false) {
293                                if (CanPatchEntries == false) {
294                                        // Only way to record size and compressed size is to append a data descriptor
295                                        // after compressed data.
296
297                                        // Stored entries of this form have already been converted to deflating.
298                                        entry.Flags |= 8;
299                                } else {
300                                        patchEntryHeader = true;
301                                }
302                        }
303                       
304                        if (Password != null) {
305                                entry.IsCrypted = true;
306                                if (entry.Crc < 0) {
307                                        // Need to append a data descriptor as the crc isnt available for use
308                                        // with encryption, the date is used instead.  Setting the flag
309                                        // indicates this to the decompressor.
310                                        entry.Flags |= 8;
311                                }
312                        }
313
314                        entry.Offset = offset;
315                        entry.CompressionMethod = (CompressionMethod)method;
316                       
317                        curMethod = method;
318                        sizePatchPos = -1;
319                       
320                        if ( (useZip64_ == UseZip64.On) || ((entry.Size < 0) && (useZip64_ == UseZip64.Dynamic)) ) {
321                                entry.ForceZip64();
322                        }
323
324                        // Write the local file header
325                        WriteLeInt(ZipConstants.LocalHeaderSignature);
326                       
327                        WriteLeShort(entry.Version);
328                        WriteLeShort(entry.Flags);
329                        WriteLeShort((byte)method);
330                        WriteLeInt((int)entry.DosTime);
331
332                        // TODO: Refactor header writing.  Its done in several places.
333                        if (headerInfoAvailable == true) {
334                                WriteLeInt((int)entry.Crc);
335                                if ( entry.LocalHeaderRequiresZip64 ) {
336                                        WriteLeInt(-1);
337                                        WriteLeInt(-1);
338                                }
339                                else {
340                                        WriteLeInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize);
341                                        WriteLeInt((int)entry.Size);
342                                }
343                        } else {
344                                if (patchEntryHeader == true) {
345                                        crcPatchPos = baseOutputStream_.Position;
346                                }
347                                WriteLeInt(0);  // Crc
348                               
349                                if ( patchEntryHeader ) {
350                                        sizePatchPos = baseOutputStream_.Position;
351                                }
352
353                                // For local header both sizes appear in Zip64 Extended Information
354                                if ( entry.LocalHeaderRequiresZip64 || patchEntryHeader ) {
355                                        WriteLeInt(-1);
356                                        WriteLeInt(-1);
357                                }
358                                else {
359                                        WriteLeInt(0);  // Compressed size
360                                        WriteLeInt(0);  // Uncompressed size
361                                }
362                        }
363
364                        byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name);
365                       
366                        if (name.Length > 0xFFFF) {
367                                throw new ZipException("Entry name too long.");
368                        }
369
370                        ZipExtraData ed = new ZipExtraData(entry.ExtraData);
371
372                        if (entry.LocalHeaderRequiresZip64) {
373                                ed.StartNewEntry();
374                                if (headerInfoAvailable) {
375                                        ed.AddLeLong(entry.Size);
376                                        ed.AddLeLong(entry.CompressedSize);
377                                }
378                                else {
379                                        ed.AddLeLong(-1);
380                                        ed.AddLeLong(-1);
381                                }
382                                ed.AddNewEntry(1);
383
384                                if ( !ed.Find(1) ) {
385                                        throw new ZipException("Internal error cant find extra data");
386                                }
387                               
388                                if ( patchEntryHeader ) {
389                                        sizePatchPos = ed.CurrentReadIndex;
390                                }
391                        }
392                        else {
393                                ed.Delete(1);
394                        }
395                       
396                        byte[] extra = ed.GetEntryData();
397
398                        WriteLeShort(name.Length);
399                        WriteLeShort(extra.Length);
400
401                        if ( name.Length > 0 ) {
402                                baseOutputStream_.Write(name, 0, name.Length);
403                        }
404                       
405                        if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) {
406                                sizePatchPos += baseOutputStream_.Position;
407                        }
408
409                        if ( extra.Length > 0 ) {
410                                baseOutputStream_.Write(extra, 0, extra.Length);
411                        }
412                       
413                        offset += ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length;
414                       
415                        // Activate the entry.
416                        curEntry = entry;
417                        crc.Reset();
418                        if (method == CompressionMethod.Deflated) {
419                                deflater_.Reset();
420                                deflater_.SetLevel(compressionLevel);
421                        }
422                        size = 0;
423                       
424                        if (entry.IsCrypted == true) {
425                                if (entry.Crc < 0) {                    // so testing Zip will says its ok
426                                        WriteEncryptionHeader(entry.DosTime << 16);
427                                } else {
428                                        WriteEncryptionHeader(entry.Crc);
429                                }
430                        }
431                }
432               
433                /// <summary>
434                /// Closes the current entry, updating header and footer information as required
435                /// </summary>
436                /// <exception cref="System.IO.IOException">
437                /// An I/O error occurs.
438                /// </exception>
439                /// <exception cref="System.InvalidOperationException">
440                /// No entry is active.
441                /// </exception>
442                public void CloseEntry()
443                {
444                        if (curEntry == null) {
445                                throw new InvalidOperationException("No open entry");
446                        }
447
448                        long csize = size;
449                       
450                        // First finish the deflater, if appropriate
451                        if (curMethod == CompressionMethod.Deflated) {
452                                if (size > 0) {
453                                        base.Finish();
454                                        csize = deflater_.TotalOut;
455                                }
456                                else {
457                                        deflater_.Reset();
458                                }
459                        }
460                       
461                        if (curEntry.Size < 0) {
462                                curEntry.Size = size;
463                        } else if (curEntry.Size != size) {
464                                throw new ZipException("size was " + size + ", but I expected " + curEntry.Size);
465                        }
466                       
467                        if (curEntry.CompressedSize < 0) {
468                                curEntry.CompressedSize = csize;
469                        } else if (curEntry.CompressedSize != csize) {
470                                throw new ZipException("compressed size was " + csize + ", but I expected " + curEntry.CompressedSize);
471                        }
472                       
473                        if (curEntry.Crc < 0) {
474                                curEntry.Crc = crc.Value;
475                        } else if (curEntry.Crc != crc.Value) {
476                                throw new ZipException("crc was " + crc.Value + ", but I expected " + curEntry.Crc);
477                        }
478                       
479                        offset += csize;
480
481                        if (curEntry.IsCrypted == true) {
482                                curEntry.CompressedSize += ZipConstants.CryptoHeaderSize;
483                        }
484                               
485                        // Patch the header if possible
486                        if (patchEntryHeader == true) {
487                                patchEntryHeader = false;
488
489                                long curPos = baseOutputStream_.Position;
490                                baseOutputStream_.Seek(crcPatchPos, SeekOrigin.Begin);
491                                WriteLeInt((int)curEntry.Crc);
492                               
493                                if ( curEntry.LocalHeaderRequiresZip64 ) {
494                                       
495                                        if ( sizePatchPos == -1 ) {
496                                                throw new ZipException("Entry requires zip64 but this has been turned off");
497                                        }
498                                       
499                                        baseOutputStream_.Seek(sizePatchPos, SeekOrigin.Begin);
500                                        WriteLeLong(curEntry.Size);
501                                        WriteLeLong(curEntry.CompressedSize);
502                                }
503                                else {
504                                        WriteLeInt((int)curEntry.CompressedSize);
505                                        WriteLeInt((int)curEntry.Size);
506                                }
507                                baseOutputStream_.Seek(curPos, SeekOrigin.Begin);
508                        }
509
510                        // Add data descriptor if flagged as required
511                        if ((curEntry.Flags & 8) != 0) {
512                                WriteLeInt(ZipConstants.DataDescriptorSignature);
513                                WriteLeInt(unchecked((int)curEntry.Crc));
514                               
515                                if ( curEntry.LocalHeaderRequiresZip64 ) {
516                                        WriteLeLong(curEntry.CompressedSize);
517                                        WriteLeLong(curEntry.Size);
518                                        offset += ZipConstants.Zip64DataDescriptorSize;
519                                }
520                                else {
521                                        WriteLeInt((int)curEntry.CompressedSize);
522                                        WriteLeInt((int)curEntry.Size);
523                                        offset += ZipConstants.DataDescriptorSize;
524                                }
525                        }
526                       
527                        entries.Add(curEntry);
528                        curEntry = null;
529                }
530               
531                void WriteEncryptionHeader(long crcValue)
532                {
533                        offset += ZipConstants.CryptoHeaderSize;
534                       
535                        InitializePassword(Password);
536                       
537                        byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize];
538                        Random rnd = new Random();
539                        rnd.NextBytes(cryptBuffer);
540                        cryptBuffer[11] = (byte)(crcValue >> 24);
541                       
542                        EncryptBlock(cryptBuffer, 0, cryptBuffer.Length);
543                        baseOutputStream_.Write(cryptBuffer, 0, cryptBuffer.Length);
544                }
545               
546                /// <summary>
547                /// Writes the given buffer to the current entry.
548                /// </summary>
549                /// <param name="buffer">The buffer containing data to write.</param>
550                /// <param name="offset">The offset of the first byte to write.</param>
551                /// <param name="count">The number of bytes to write.</param>
552                /// <exception cref="ZipException">Archive size is invalid</exception>
553                /// <exception cref="System.InvalidOperationException">No entry is active.</exception>
554                public override void Write(byte[] buffer, int offset, int count)
555                {
556                        if (curEntry == null) {
557                                throw new InvalidOperationException("No open entry.");
558                        }
559                       
560                        if ( buffer == null ) {
561                                throw new ArgumentNullException("buffer");
562                        }
563                       
564                        if ( offset < 0 ) {
565#if NETCF_1_0
566                                throw new ArgumentOutOfRangeException("offset");
567#else
568                                throw new ArgumentOutOfRangeException("offset", "Cannot be negative");
569#endif
570                        }
571
572                        if ( count < 0 ) {
573#if NETCF_1_0
574                                throw new ArgumentOutOfRangeException("count");
575#else
576                                throw new ArgumentOutOfRangeException("count", "Cannot be negative");
577#endif
578                        }
579
580                        if ( (buffer.Length - offset) < count ) {
581                                throw new ArgumentException("Invalid offset/count combination");
582                        }
583                       
584                        crc.Update(buffer, offset, count);
585                        size += count;
586                       
587                        switch (curMethod) {
588                                case CompressionMethod.Deflated:
589                                        base.Write(buffer, offset, count);
590                                        break;
591                               
592                                case CompressionMethod.Stored:
593                                        if (Password != null) {
594                                                CopyAndEncrypt(buffer, offset, count);
595                                        } else {
596                                                baseOutputStream_.Write(buffer, offset, count);
597                                        }
598                                        break;
599                        }
600                }
601               
602                void CopyAndEncrypt(byte[] buffer, int offset, int count)
603                {
604                        const int CopyBufferSize = 4096;
605                        byte[] localBuffer = new byte[CopyBufferSize];
606                        while ( count > 0 ) {
607                                int bufferCount = (count < CopyBufferSize) ? count : CopyBufferSize;
608                               
609                                Array.Copy(buffer, offset, localBuffer, 0, bufferCount);
610                                EncryptBlock(localBuffer, 0, bufferCount);
611                                baseOutputStream_.Write(localBuffer, 0, bufferCount);
612                                count -= bufferCount;
613                                offset += bufferCount;
614                        }
615                }
616               
617                /// <summary>
618                /// Finishes the stream.  This will write the central directory at the
619                /// end of the zip file and flush the stream.
620                /// </summary>
621                /// <remarks>
622                /// This is automatically called when the stream is closed.
623                /// </remarks>
624                /// <exception cref="System.IO.IOException">
625                /// An I/O error occurs.
626                /// </exception>
627                /// <exception cref="ZipException">
628                /// Comment exceeds the maximum length<br/>
629                /// Entry name exceeds the maximum length
630                /// </exception>
631                public override void Finish()
632                {
633                        if (entries == null)  {
634                                return;
635                        }
636                       
637                        if (curEntry != null) {
638                                CloseEntry();
639                        }
640                       
641                        long numEntries = entries.Count;
642                        long sizeEntries = 0;
643                       
644                        foreach (ZipEntry entry in entries) {
645                                WriteLeInt(ZipConstants.CentralHeaderSignature);
646                                WriteLeShort(ZipConstants.VersionMadeBy);
647                                WriteLeShort(entry.Version);
648                                WriteLeShort(entry.Flags);
649                                WriteLeShort((short)entry.CompressionMethod);
650                                WriteLeInt((int)entry.DosTime);
651                                WriteLeInt((int)entry.Crc);
652
653                                if ( entry.IsZip64Forced() ||
654                                        (entry.CompressedSize >= uint.MaxValue) )
655                                {
656                                        WriteLeInt(-1);
657                                }
658                                else {
659                                        WriteLeInt((int)entry.CompressedSize);
660                                }
661
662                                if ( entry.IsZip64Forced() ||
663                                        (entry.Size >= uint.MaxValue) )
664                                {
665                                        WriteLeInt(-1);
666                                }
667                                else {
668                                        WriteLeInt((int)entry.Size);
669                                }
670
671                                byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name);
672                               
673                                if (name.Length > 0xffff) {
674                                        throw new ZipException("Name too long.");
675                                }
676                               
677                                ZipExtraData ed = new ZipExtraData(entry.ExtraData);
678
679                                if ( entry.CentralHeaderRequiresZip64 ) {
680                                        ed.StartNewEntry();
681                                        if ( entry.IsZip64Forced() ||
682                                                (entry.Size >= 0xffffffff) )
683                                        {
684                                                ed.AddLeLong(entry.Size);
685                                        }
686
687                                        if ( entry.IsZip64Forced() ||
688                                                (entry.CompressedSize >= 0xffffffff) )
689                                        {
690                                                ed.AddLeLong(entry.CompressedSize);
691                                        }
692
693                                        if ( entry.Offset >= 0xffffffff )
694                                        {
695                                                ed.AddLeLong(entry.Offset);
696                                        }
697
698                                        ed.AddNewEntry(1);
699                                }
700                                else {
701                                        ed.Delete(1);
702                                }
703
704                                byte[] extra = ed.GetEntryData();
705                               
706                                byte[] entryComment =
707                                        (entry.Comment != null) ?
708                                        ZipConstants.ConvertToArray(entry.Flags, entry.Comment) :
709                                        new byte[0];
710
711                                if (entryComment.Length > 0xffff) {
712                                        throw new ZipException("Comment too long.");
713                                }
714                               
715                                WriteLeShort(name.Length);
716                                WriteLeShort(extra.Length);
717                                WriteLeShort(entryComment.Length);
718                                WriteLeShort(0);        // disk number
719                                WriteLeShort(0);        // internal file attributes
720                                                                        // external file attributes
721
722                                if (entry.ExternalFileAttributes != -1) {
723                                        WriteLeInt(entry.ExternalFileAttributes);
724                                } else {
725                                        if (entry.IsDirectory) {                         // mark entry as directory (from nikolam.AT.perfectinfo.com)
726                                                WriteLeInt(16);
727                                        } else {
728                                                WriteLeInt(0);
729                                        }
730                                }
731
732                                if ( entry.Offset >= uint.MaxValue ) {
733                                        WriteLeInt(-1);
734                                }
735                                else {
736                                        WriteLeInt((int)entry.Offset);
737                                }
738                               
739                                if ( name.Length > 0 ) {
740                                        baseOutputStream_.Write(name,    0, name.Length);
741                                }
742
743                                if ( extra.Length > 0 ) {
744                                        baseOutputStream_.Write(extra,   0, extra.Length);
745                                }
746
747                                if ( entryComment.Length > 0 ) {
748                                        baseOutputStream_.Write(entryComment, 0, entryComment.Length);
749                                }
750
751                                sizeEntries += ZipConstants.CentralHeaderBaseSize + name.Length + extra.Length + entryComment.Length;
752                        }
753                       
754                        using ( ZipHelperStream zhs = new ZipHelperStream(baseOutputStream_) ) {
755                                zhs.WriteEndOfCentralDirectory(numEntries, sizeEntries, offset, zipComment);
756                        }
757
758                        entries = null;
759                }
760               
761                #region Instance Fields
762                /// <summary>
763                /// The entries for the archive.
764                /// </summary>
765                ArrayList entries  = new ArrayList();
766               
767                /// <summary>
768                /// Used to track the crc of data added to entries.
769                /// </summary>
770                Crc32 crc = new Crc32();
771               
772                /// <summary>
773                /// The current entry being added.
774                /// </summary>
775                ZipEntry  curEntry;
776               
777                int defaultCompressionLevel = Deflater.DEFAULT_COMPRESSION;
778               
779                CompressionMethod curMethod = CompressionMethod.Deflated;
780
781                /// <summary>
782                /// Used to track the size of data for an entry during writing.
783                /// </summary>
784                long size;
785               
786                /// <summary>
787                /// Offset to be recorded for each entry in the central header.
788                /// </summary>
789                long offset;
790               
791                /// <summary>
792                /// Comment for the entire archive recorded in central header.
793                /// </summary>
794                byte[] zipComment = new byte[0];
795               
796                /// <summary>
797                /// Flag indicating that header patching is required for the current entry.
798                /// </summary>
799                bool patchEntryHeader;
800               
801                /// <summary>
802                /// Position to patch crc
803                /// </summary>
804                long crcPatchPos = -1;
805               
806                /// <summary>
807                /// Position to patch size.
808                /// </summary>
809                long sizePatchPos = -1;
810
811                // Default is dynamic which is not backwards compatible and can cause problems
812                // with XP's built in compression which cant read Zip64 archives.
813                // However it does avoid the situation were a large file is added and cannot be completed correctly.
814                // NOTE: Setting the size for entries before they are added is the best solution!
815                UseZip64 useZip64_ = UseZip64.Dynamic;
816                #endregion
817        }
818}
Notatka: Zobacz TracBrowser aby uzyskać więcej informacji.