Giter Club home page Giter Club logo

sharpziplib's Introduction

SharpZipLib Build Status NuGet Version openupm

Introduction

SharpZipLib (#ziplib, formerly NZipLib) is a compression library that supports Zip files using both stored and deflate compression methods, PKZIP 2.0 style and AES encryption, tar with GNU long filename extensions, GZip, zlib and raw deflate, as well as BZip2. Zip64 is supported while Deflate64 is not yet supported. It is implemented as an assembly (installable in the GAC), and thus can easily be incorporated into other projects (in any .NET language). The creator of SharpZipLib put it this way: "I've ported the zip library over to C# because I needed gzip/zip compression and I didn't want to use libzip.dll or something like this. I want all in pure C#."

SharpZipLib was originally ported from the GNU Classpath java.util.zip library for use with SharpDevelop, which needed gzip/zip compression. bzip2 compression and tar archiving were added later due to popular demand.

The SharpZipLib homepage has precompiled libraries available for download, API documentation, release history, samples and more.

License

This software is now released under the MIT License. Please see issue #103 for more information on the relicensing effort.

Previous versions were released under the GNU General Public License, version 2 with an exception which allowed linking with non-GPL programs.

Namespace layout

Module Namespace
BZip2 implementation ICSharpCode.SharpZipLib.BZip2.*
Checksum implementation ICSharpCode.SharpZipLib.Checksum.*
Core utilities / interfaces ICSharpCode.SharpZipLib.Core.*
Encryption implementation ICSharpCode.SharpZipLib.Encryption.*
GZip implementation ICSharpCode.SharpZipLib.GZip.*
LZW implementation ICSharpCode.SharpZipLib.Lzw.*
Tar implementation ICSharpCode.SharpZipLib.Tar.*
ZIP implementation ICSharpCode.SharpZipLib.Zip.*
Inflater/Deflater ICSharpCode.SharpZipLib.Zip.Compression.*
Inflater/Deflater streams ICSharpCode.SharpZipLib.Zip.Compression.Streams.*

Credits

SharpZipLib was initially developed by Mike Krüger. Past maintainers are John Reilly, David Pierson and Neil McNeight.

And thanks to all the people that contributed features, bug fixes and issue reports.

sharpziplib's People

Contributors

adamreeve avatar bastianeicher avatar charlesgriffiths avatar christophwille avatar creker avatar davidpierson avatar decipherer avatar dependabot[bot] avatar dubois avatar flensrocker avatar helios-vmg avatar hempels avatar hultqvist avatar hypersw avatar jfreilly avatar mailaender avatar mcneight avatar michaelaird avatar mkrueger avatar nathan-c avatar novn2013 avatar nsgomez avatar numpsy avatar piksel avatar ronaldbarendse avatar siegfriedpammer avatar suchiman avatar viktorhofer avatar yihezkel avatar zone117x avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sharpziplib's Issues

Bug in DropPathRoot - IndexOutOfBoundsException

There is a bug in DropPathRoot (in WindowsPathUtils.cs / ICSharpCode.SharpZipLib.Core.WindowsPathUtils) that causes an IndexOutOfBoundsException:

This can be seen for paths such as "\server". It works correctly (as it is) for paths such as "\server\share".

is:

// Scan for two separate elements \\machine\share\restofpath
while ((index <= path.Length) &&
    (((path[index] != '\\') && (path[index] != '/')) || (--elements > 0))) {
    index++;
}

should likely be (but I think other modifications will be needed as well to obtain desired behavior):

// Scan for two separate elements \\machine\share\restofpath
while ((index < path.Length) &&
    (((path[index] != '\\') && (path[index] != '/')) || (--elements > 0))) {
    index++;
}

Also, since "index" starts at 2, a few lines above, I'm not sure what the purpose of "elements" is -- possibly a left over?

Thoughts?

How to zip file which compatible with pkzip 2.0 or above?

Hi,
I am trying to zip files that need to be compatible with PkZip 2.0 or above. My code for Zip file is ;

var fsOut = File.Create(contentfile);
var zipStream = new ZipOutputStream(fsOut);

zipStream.SetLevel(2);
var newEntry = new ZipEntry(Path.GetFileName(filepath));
zipStream.PutNextEntry(newEntry);
var buffer = new byte[4096];
using (var streamReader = File.OpenRead(filepath))
{
   StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();

zipStream.IsStreamOwner = true;
zipStream.Close();

So what should I need to do to achieve the compatibility.

FastZip exception when attempting to add locked file not well handled

SD-1369, originally created on 7/27/2007 13:17:35 by John Reilly

FastZip::AddFileContents can throw an exception at the using (FileStream
stream = File.OpenRead(name)) if the file is locked by another process. 
The exception is not caught until ZipOutputStream::CloseEntry() ~ line
483 where it checks the size.  Returns an error "size was 0 but I
expected dddddd".  This leaves the user with little indication of the
problem.

..

The above is likely already fixed, but a new enhancement is needed.

Add a new property to allow the adding of files that re open by another
for writing. This would change the FileShare parameter in File.Open to
ReadWrite.

Also update the NUnit test to set the property.

Forum thread
community.sharpdevelop.net/forums/t/16183.aspx


Comment from John Reilly on 7/27/2007 13:20:04:
Originated from forum post 18110.

Presumably using events would help to pick up on this somewhat more
elegantly.


Comment from David Pierson on 2/19/2010 04:59:10:
This may be related to this issue in this post ...

http://community.sharpdevelop.net/forums/t/10314.aspx

Adding a file to existing archive fails silently

SD-1386, originally created on 1/5/2008 21:12:01 by John Reilly

 I've tracked down where the exception is thrown intitally (before being
caught in RunUpdates() and not being rethrown). It's in this function:

 AddEntry(ZipFile workFile, ZipUpdate update)

 Specifically:

                if ( update.OutEntry.Size != sourceStreamLength ) {
                     throw new ZipException("Entry size/stream size
mismatch");

 

I started having trouble when Zip64 was being used by default with SVN
builds earlier this summer. I solved the problem by turning off the
Zip64 both when the archive is intially created and when new files are
added. I can't help but think the size mismatch problems I was having
before are related to Zip64 stuff and have dug themselves deeper into
the SharpZipLib code. Now, with Zip64 either on and off, this exception
is thrown.

It's the "update.OutEntry.Size" which has the wrong value; the
sourceStreamLength is correct. I've solved the problem in a hackish way:

                    long sourceStreamLength = source.Length;
                    //if ( update.OutEntry.Size < 0 ) {
                        update.OutEntry.Size = sourceStreamLength;
                    //}
                    //else {
                        // Check for errant entries.
                    //    if ( update.OutEntry.Size !=
sourceStreamLength ) {
                    //        throw new ZipException("Entry size/stream
size mismatch");
                    //    }
                    //}

And it works everytime. Also, to assure you that the code I used to
create the intial archive is correct, I've created an archive with the
exact same files using 7-zip, and then over-writing the "afile.txt"
using:

            using (ZipFile zipFile = new ZipFile(zipfileloc))
            {
                zipFile.BeginUpdate();

                zipFile.Add(new MemoryDataSource(ClientFileToArray()),
"afile.txt");

                zipFile.CommitUpdate();
            } 

and I get the same failure.

 

So, from what it looks like, the misread value occurs only when the
archive is being re-opened before re-writing the temp archive. I can
provide you with the files I use if it will help you track down the bug.


Comment from John Reilly on 1/5/2008 21:12:53:
Check this out to confirm its a problem.


Comment from David Pierson on 3/2/2010 03:21:39:
Updates will no longer fail silently (version 0.86 onwards). This is
fixed under ZIP-1650.

The issue raised here of the test throwing an exception, remains
outstanding.
There is a good chance it may be the same underlying issue -- i.e. an
incorrect calculation of the size of the entry -- as reported in
ZIP-1650.

Tar ASCII translation does not work

SD-744, originally created on 4/2/2006 22:23:38 by John Reilly

I have met just a little prbl whith TAR.GZ files when I set the
asciiTranslate option on "true". When this option is set on false,
everything works great, but when it is on true, an IOException appears
:(

Here is the full error message :


Une exception non gérée du type 'System.IO.IOException' s'est produite
dans mscorlib.dll

Informations supplémentaires : Le processus ne peut pas accéder au
fichier "C:\Documents and Settings\Jeje\Mes documents\Visual Studio
Projects\TestXLAccess\bin\Debug\Test\batchs\purge.sh", car il est
en cours d'utilisation par un autre processus.


I guess you prefer in English ;-)


A non handeled exception of  'System.IO.IOException' type has occured in
mscorlib.dll

Further information : The process cannot access to the file
"C:\Documents and Settings\Jeje\Mes documents\Visual Studio
Projects\TestXLAccess\bin\Debug\Test\batchs\purge.sh", because it
is being used by an other process


So, I think SharpZipLib might create a new process to write into text
files but there is a colision with the main process which has created
the file or something like that.

If you have any idea about how this little bug could be resolved, I
would be glad to hear it :)

Thx again for your work.
Jerome

Tar file modification times: nanoseond resolution and restore

SD-1310, originally created on 2/9/2007 00:11:51 by John Reilly

What kind of effort would be required to implement nanosecond resolution
for file modification times for the Tar format?  This was implemented in
GNU Tar 1.16, and I would find support for this in SharpZipLib to be
very useful.

From Thread 15102 in forum.

Related issue:
Add a  TarArchive.RestoreDateTimeOnExtract  bool property similar to
that in FastZip.
Currently the ExtractContents method results in created files having
the date/time of extraction. Perhaps also a flag to allow setting
Creation time and/or Modification time.

Forum thread
11551
and thread
15930.

Filename access isnt supported

SD-354, originally created on 4/26/2005 21:20:24 by John Reilly

The reading and writing of fields and the associated flags in gzip
headers isn't supported.

bit 0 FTEXT
bit 1 FHCRC
bit 2 FEXTRA
bit 3 FNAME

Windows Store app library error

Could not install package 'SharpZipLib 0.86.0'. You are trying to install this package into a project that targets '.NETCore,Version=v4.5.1', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

Disparity between versions

SD-332, originally created on 2/20/2005 11:51:18 by John Reilly

Seems to be a disparity between versions and what can be compressed
/decompressed.

We are using a prior version of SharpZipLib and recently noticed a
problem when compressing very large data - after the data was compressed
it could not be uncompressed without an exception being thrown. We
upgraded to the most recent version which corrected that problem, but,
it introduced a more serious problem. We could not uncompress ANY of the
data that had been compressed with the prior version - we save
compressed data in a database for retrieval at a later time.

The exception we get is:

"BZip2 input stream bad block header"

ICSharpCode.SharpZipLib.BZip2.BZip2InputStream.BadBlockHeader()

at ICSharpCode.SharpZipLib.BZip2.BZip2InputStream.InitBlock()

at ICSharpCode.SharpZipLib.BZip2.BZip2InputStream..ctor(Stream stream)

We can use the same code and switch back to the previous version of
SharpZipLib and then we are able to successfully uncompress the data
that was compressed with that same prior version. It seems like
SharpZipLib will only uncompress data that was compressed with the same
version. Is this correct?

Here is the code where the Exception is thrown.

public static byte[] DecompressToBytes(byte[] bytesToDecompress)

{

byte[] writeData = new byte[4096];

Stream inStream = null;

MemoryStream outStream = new MemoryStream();

try

{

--->>>> inStream = new BZip2InputStream(new
MemoryStream(bytesToDecompress));

}

catch(Exception e)

{

throw e;

}

 

 

-- Brian Shepler

-- [email protected]

Set entry date when using ZipFile?

Hi,
I can't see how to set the entry date when using the ZipFile class.

I tried adding a ZipEntry with DateTime set appropriately but I got an error:

Entry cannot have any data

The code is on line 1737 of ZipFile.cs:

    public void Add(ZipEntry entry)
    {
        if ( entry == null ) {
            throw new ArgumentNullException("entry");
        }

        CheckUpdating();

        if ( (entry.Size != 0) || (entry.CompressedSize != 0) ) {
            throw new ZipException("Entry cannot have any data");
        }

        AddUpdate(new ZipUpdate(UpdateCommand.Add, entry));
    }

Is what I want to do possible?

It would be great to use ZipFile over ZipOutputStream, I want to archive some files into a single zip as part of a maintenance process.

Regards

Unzipping file does not work on WP

I am trying to unzip a file stored in isolated storage. The class ZipFile for which i am sending the correct path does not accept the string input. Could you please help me what is the problem

TarOutputStream doesn't flush buffer on Finish()

When you call Finish() on the TarOutputStream, it doesn't flush everything.

Finish():

    public void Finish()
    {
        if ( IsEntryOpen ) 
        {
            CloseEntry();
        }
        WriteEofBlock();
    }

However, Close() includes a buffer.Close() call:

    public override void Close()
    {
        if ( !isClosed )
        {
            isClosed = true;
            Finish();
            buffer.Close();
        }
    }

This effectively flushes the TarBuffer. The upshot is that, if you want to have all of the data flushed, you need to close the TarOutputStream, which will automatically close the Stream object that you gave it. The exception for this is with the GZIP functionality, whose GzipOutputStream has a IsStreamOwner property that provides you the option of -not- closing the base stream.

This means that in order to get all of the data out of the Stream, you need to either use a MemoryStream wrapped by GzipOutputStream, or use a FileStream so that you can recover the data after the mandatory close.

Deflate64

SD-183, originally created on 7/21/2004 21:04:18 by John Reilly

Goes hand in hand with Zip64 pretty much, gives better compression that
standard deflate


Comment from David Pierson on 9/2/2010 02:00:49:
"Deflate64 is a proprietary and undocumented extension of the protocol"

Do we really want to do this in an open source project?

4 failing tests from initial pull

It seems that 4 unit tests fail namely:

  • BZip2Suite - Performance
    Expected True But Was False
  • GZipTestSuite - ZeroLengthInputStream
    reading from an empty stream should cause an exception
  • TarTestSuite - LongNames
    Name match failure Expected string length 513 but was 512
  • FastZipHandling - ReadingOfLockedDataFiles
    The process cannot access the file 'C:\Users\solomonst\AppData\Local\Temp\a.dat' because it is being used by another process.

I wanted to confirm that this is the case for everyone before moving forward, the last one is actually the error i forked the project to fix

Tar extraction - Confirm wether this is an issue or not

SD-749, originally created on 4/4/2006 04:54:45 by John Reilly

Hi , I am using SharZipLib for tar archive managment and I get a
problem:
When I list the content of my archive ( in order to know how many item 
it contains ), the  ExtractContents method don't extract anythings.

For example , With this code, nothing is extract :
            m_tarArchive = TarArchive.CreateInputTarArchive( tarStream
);
  
            m_tarItemCount = 0;
            ProgressMessageHandler countHandler = new
ProgressMessageHandler( CountTarEntry );
            ProgressMessageHandler notifyHandler = new
ProgressMessageHandler( NotifiTarExtract );
            m_tarArchive.ProgressMessageEvent += countHandler;
            m_tarArchive.ListContents();
            m_tarArchive.ProgressMessageEvent -= countHandler;
            m_tarArchive.ProgressMessageEvent += notifyHandler;
           
            m_tarArchive.ExtractContents( restoreBaseDirectory );
            m_tarArchive.CloseArchive();

If I comment the m_tarArchive.ListContents(); line,  archive content is
extract in restoreBaseDirectory.
Any ideas?
Thanks,

Nicolas

FileInfo-Problem with Daylight saving time

I have written an application that uses the ZipEntry class to add files to a zip file.

The file to be zipped, was created in the winter time (December 1, 2012 11:00 AM).
The zip file was created on a Windows Server 2003.

In the zip file, the file has the following date (December 1, 2012 10:00 AM)

It does not matter if I give the correct date via 'Zipentry.Datetime' or not.

When you unzip the file via Winzip the date is also wrong.

The ZipEntry class seems to have a problem with the summer and winter time.

ZipOutputStream copy all arborescence

Hi,

I watched and followed your tutorial download for IIS.

I have a concern however. The zip file contains the absolute path to the directory or file. I would like to know how it starts specified or recursion.

let me explain:

c:/toto/tutu/MyProject/zip/Project1/*

become :

Project1/*

on Project1.zip

AES Support

SD-1649, originally created on 2/22/2010 08:18:51 by David Pierson

Add 128 and 256 bit AES support compatible with WinZip's
implementation.


Comment from David Pierson on 2/22/2010 08:21:57:
Mostly implemented. Creation via Zipfile and ZipOutputStream, and
extraction via ZipFile is now handled (r499).
Extraction via ZipInputStream is not implemented. FastZip is not
implemented.


Progress:

  • Archive creation:
    • Key sizes:
      • 128 bit
      • 192 bit¹
      • 256 bit
    • API support:
      • Zipfile
      • ZipOutputStream
  • Archive extraction:
    • Key sizes:
      • 128 bit
      • 192 bit¹
      • 256 bit
    • API support:
      • Zipfile (Should be working?)
      • ZipInputStream - PR WIP #381
      • FastZip

¹ Creation of archives with 192-bit key is not supported in any of the leading archiving applications (WinRAR, WinZip, 7-zip, info-zip, Keka).

Tar formats for files over 8GB such as Posix and Pax

SD-1647, originally created on 2/19/2010 05:02:23 by David Pierson

Current code matches the traditional tar format and limits the size of
an individual file being added to a tar to 8GB. (However, it can read up
to 64GB).

There are several format extensions that skirt this, such as GNU, PAX
and POSIX.

GNU tar sets a bit in MSB of size field to specify that the content
should be interpreted as binary field instead of octal digits.
Pax on the other hand uses a type flag to specify some tar header field
has been extended by the next immediate block where for example,
filesize is written as a plain ascii string - the format is of a
"key=value" with other fields such as name being able to be extended
similarly.

http://community.sharpdevelop.net/forums/t/141.aspx


Comment from David Pierson on 7/27/2012 08:54:18:
Email received from Ivan Peev 26 Apr 2012 with code to update TarHeader
to extract Tar files over 8GB using binary instead of ascii.


Comment from David Pierson on 11/8/2012 06:20:10:
Implemented the binary field approach in August 2012 in this commit

a74a385
but not the PAX key=value.

Add files to zip more efficiently

SD-1881, originally created on 1/27/2012 06:22:03 by David Pierson

The ability to add to a zip more efficiently has been asked for.

  1. When the source is already zipped, to add to another zip (either
    with BeginUpdate/Add/Commit or via standard zip creation) requires
    unpacking and repacking. For efficiency allow adding already compressed
    data.

  2. When updating, the process requires disk or memory for a temporary
    copy. Requested to add to a zip without either.

Threads:
Add files to a zip without saving temp
files

Filecount related problem

Need to scan for a particular file in a group of large zipfiles.
Usually FindEntry returns the entryid as a positive integer, however these zipz may have 35,000 or more files in them which is returning (-1) for the ID. The target file is in the zip, but I cannot seems to inflate/extract it.

Seems like the Entry ID is an int16 (limit 32,767) - is there a work around? I have no control over the zip compositing phase so there are some large zips to deal with.

Guessing worst case - extract everything, then use file system to select and effect process.

Better ideas?

Thanks much,
Tom

Create/Extract NTFS Extra Data field for Timestamp etc

SD-1800, originally created on 12/20/2010 01:58:10 by David Pierson

We should have the ability to create the NTFS Extra Data field (0x000a)
via an option in FastZip, and an easy way to create it in ZipFile and
ZipOutputStream.

This would hold the NTFS Last Modified timestamp, avoiding the problem
of the 2 second granularity of the standard entry timestamp.

Relevant forum threads:

http://community.sharpdevelop.net/forums/t/12411.aspx

http://community.sharpdevelop.net/forums/t/14178.aspx

Encryption needs refactoring

SD-122, originally created on 5/24/2004 10:18:54 by John Reilly

Encryption as of v0.84 has been partially refactored and needs
completing.

Also further refactoring is required to allow compact framework to be
able to build again.

Originally it was implemented for Zip files only but was partially
placed in classes that are used by other algorithms. It would be good to
look at allowing other encryption algorithms and reworking things so Zip
encryption is for Zip code only. This comes back to design more than
refactoring.


Comment from John Reilly on 8/9/2007 12:22:05:
DeflatorOutputStream has been improved to support all frameworks for
encryption.

This is still not complete however.

BZip2InputStream CanSeek should be false

The BZip2InputStream CanSeek property should return false instead of the baseStream.CanSeek, as the seek function throws an exception stating that it cannot seek.

Zip64 Archive cannot be updated

The code from https://github.com/icsharpcode/SharpZipLib/wiki/Updating will not work if a Zip64 archive is used.

Instead the following error will occur:
ZipException: "Extra data extended Zip64 information length is invalid"
or alternatively (if zipFile.CommitUpdate() is executed in QuickWatch):
"BeginUpdate has not been called"

it works fine if a Zip file which was generated with UseZip64.Off is being updated.

Manual TAR building may be broken.

I'm trying to build a TAR (no compression) on a MemoryStream using strings (rather than physical files). It always produces zero bytes.

        Stream tarStream = new MemoryStream();
        TarOutputStream tarOutput = new TarOutputStream(tarStream);

        TarArchive tarArchive = TarArchive.CreateOutputTarArchive(tarOutput);
        TarEntry tarEntry;

        // Insert root entry.

        tarEntry = TarEntry.CreateTarEntry("root/");
        tarOutput.PutNextEntry(tarEntry);
        tarOutput.CloseEntry();

        // Insert file.

        string testBody1 = "This is a test (1).";
        tarEntry = TarEntry.CreateTarEntry("abc");
        tarEntry.Size = testBody1.Length;

        tarOutput.PutNextEntry(tarEntry);
        tarOutput.Write(Encoding.ASCII.GetBytes(testBody1), 0, testBody1.Length);
        tarOutput.CloseEntry();

        // Read some data.

        byte[] buffer = new byte[512];
        int written = tarStream.Read(buffer, 0, 512);//.ReadAllBytes();

        tarOutput.Close();

This creates four blocks, but never seems to write the data from recordBuffer to outputStream. WriteRecord() is never called. Specifically:

        if (currentBlockIndex >= BlockFactor) {
            WriteRecord();
        }

I could reduce BlockFactor, but I shouldn't have to.

Calling Close or Dispose on zip entry stream, and finalizers

SD-1880, originally created on 1/27/2012 05:55:20 by David Pierson

Several posters have reported issues when calling Flush Close and
Dispose on the stream they get from GetInputStream.

Worth remarking for any readers, it is recommended not to call any of
those methods against the entry stream.

Threads:
System.ObjectDisposedException: Cannot access a closed
file

http://community.sharpdevelop.net/forums/t/14397.aspx

Even without calling Close/Dispose the .NET GC may finalise the outer
stream while still using the entry stream. Believe this has been fixed
in 0.85.5 - worth desk checking.
Thread:
Random bug while
unzipping

"There is a flaw in the dispose method of ZipFile also which isnt
checking for disposing before closing streams. The f
inalizer for ZipFile can indeed be removed as Daniel states.  There is
nothing for it to do once you correct the flaw above."

ZipInputStream class doesn't process correctly no compression entries with flag Bit 3 set

The PKZIP documentation here states for general purpose flag Bit 3:

"If this bit is set, the fields crc-32, compressed size and uncompressed size are set to zero in the local header. The correct values are put in the data descriptor immediately following the compressed data. (Note: PKZIP version 2.04g for DOS only recognizes this bit for method 8 compression, newer versions of PKZIP recognize this bit for any compression method.)".


The CRC, compressed and uncompressed size will be 0 and the extraction fails.

Extend VB samples

SD-1195, originally created on 11/6/2006 03:19:07 by John Reilly

The Vb samples are not as full as the C# ones and cause a fair bit of
traffic in the forum.  Extending these would help greatly.

ZipFile.delete(ZipEntry) doesnt work!?

Hello,

in the wiki is no command reference for ".delete" on ZipFiles.

I used this code snippet and it doesnt work.

Dim a As New ZipFile(CurDir() & "\a.zip")
Try

    Try
        a.BeginUpdate()
    Catch ex As Exception
    End Try

    For Each tee As ZipEntry In a
        If tee.Name.Length >= 8 And tee.IsDirectory = False Then
            If tee.Name.Substring(0, 8).ToLower.Equals("12345678") Then
                a.Delete(tee)
            End If
        End If
    Next

    a.CommitUpdate()

Catch ex As Exception
    MessageBox.Show(ex.Message)
End Try

a.Close()

I would remove a complete directory.

Archive Structure
fail delete

ZipUpdate fails when updating Open Document(ODT) files

SD-1650, originally created on 2/22/2010 23:59:25 by David Pierson

Using ZipUpdate to modify an ODT (Open Document) archive will fail
silently.

This issue is confined to updates when the ZipFile is constructed from
a MemoryStream holding the zip file bytes. The use of a MemoryStream as
data source results in a different codepath in RunUpdates, where the
directUpdate flag is true and updates are applied inline. When the
datasource is a disk file, updates are applied via a temporary ZipFile
object using secondary memory storage, avoiding the complexities of the
inline update. 

The exception "Failed to copy bytes expected nnn read 0" occurs in
RunUpdates -> CopyEntryDirect -> CopyEntryDataDirect.

The silent fail is due to the exception being caught and discarded in
RunUpdates.

See
community.sharpdevelop.net/forums/t/10314.aspx
for suggested fix.


Comment from David Pierson on 2/23/2010 04:29:08:
This may be related to another bug ticket
ZIP-1386


Comment from David Pierson on 3/2/2010 03:20:00:
Applied code fix, committed as revision 502 (ZipFile.cs).

Outstanding issue of why the offset calculation is wrong. Leaving this
ticket open to followup on issue marked in code with comment ...
  // TODO: Find out why this calculation comes up 4 bytes short on some
entries in ODT (Office Document Text) archives.

Also resolved issue of updates failing silently. Exceptions in the
update will no longer be swallowed.

Tar extraction disk / directory

SD-1674, originally created on 6/3/2010 06:12:44 by David Pierson

The TarArchive.ExtractContents(string destinationDirectory) method does
not allow control over extraction in terms of resulting target folders.
See

community.sharpdevelop.net/forums/t/11321.aspx

Also, it always strips off the drive spec from the entry name, and
overwrites this with the destinationDirectory spec. If you want to keep
the drive spec in the tar, leaving that blank does not work. See

community.sharpdevelop.net/forums/t/10875.aspx

Provide a way to allow some control.
Or just suggest via sample a way using the example in the
11322

thread using TarInputStream.

Tar filenames with national characters not correctly stored.

SD-406, originally created on 8/9/2005 12:00:36 by John Reilly

Hello,
I have this problem:
When adding files with national characters in filenames to the
tar, the tar is corrupted (e.g. PowerArchiver can't extract it. It can
do it with itself-created TAR with the same contents (files), so the
problem is definitely on #ziplib side )

The code
Console.WriteLine("Adding file '"+ entry.Name +"'");
writes the entry's filename right.

Is there some way to push #ziplib to support national characters in
filenames? (or should I use other format/library?)

Thank you very much

Two zip files with identical content are not identical

Using the default compression level if I create a new zip file twice with the same content the zip files created will not be byte for byte identical. Zip files with small content are identical but with larger content (e.g.3mb) the zip files are not the same. The content is fine and is identical when extracted.

I have a need to have the zip files to be identical if the content is identical.

Note that I am not using any encryption.

Does anyone know why they are not identical and can I do anything about it?

Thanks

Ignore "Compressed size mismatch" error from Xceed

SD-1801, originally created on 12/20/2010 02:06:14 by David Pierson

When a password is applied, Xceed is incorrectly setting values in the
local header. This results in a “Compressed size mismatch between
central header(2399) and local header(0)” exception in
ZipFile.TestLocalHeader.

Sample code in ZipFile.cs at line 1259 ...

if (compressedSize != entry.CompressedSize &&
                        compressedSize != 0xFFFFFFFF && compressedSize
!= -1**&& compressedSize != 0**) {
                        throw new ZipException(
                            string.Format("Compressed size mismatch
between central header({0}) and local header({1})",
                            entry.CompressedSize, compressedSize));
                    }

Forum thread:

http://community.sharpdevelop.net/forums/t/12404.aspx
"Errors unzipping zip files created using Xceed V4.0"

UnZip write to file endlessly.

I unzip a zip file which has some crc error. When I use SharpZipLib to unzip it, it will write to target file endlessly. I found the FileStream.position isn't always changed. Inflater.DecodeHuffman always return true value.

Bug in OutputWindow.cs that will cause ZipInputStream.Read() to never run out of data in certain corrupt ZIP files

HI there, I recently discovered a potential bug in Zip/Compression/Streams/OutputWindow.cs that, when combined with a corrupt ZIP archive, may cause ZipInputStream.Read() to never run out of data.

Specifically, in line 208 (version 0.86.0.518):

    copyEnd = (windowEnd - windowFilled + len) & WindowMask;

Where copyEnd is supposed to be a positive index into the window. However, given a ZIP archive that is corrupt in a particular way (I have an example ZIP file that triggers this behavior), (windowEnd - windowFilled + len) will become negative. However, the "& WindowMask" operator masks off the high bits, which converts the number back to positive. This throws off the subsequent logic and will set the code into an infinite loop where the ZipInputStream.Read() calls always returns "new" data, and therefore never return "0".

So I made a simple modification that first checks to see if (windowEnd - windowFilled + len) is negative. If that's the case, I simply throw a "WIndow overflow" error, something like this.

            int endOffset = windowEnd - windowFilled + len;
            if (endOffset < 0) {
                throw new InvalidOperationException("Window overflow");
            }
            copyEnd = endOffset & WindowMask;

This seems to correctly detect the corruption and throw an exception.

I think there must be more elegant ways to fix this, but this quick-and-dirty trick did it for me. I wnt to re-iterate that this only happens (as far as I know) when the ZIP file is corrupt, but since I have to deal with ZIP files that are created by others, this does come in handy. Hope this might be helpful to someone.

  • K.

is the ZipEntry filename must encoded using codepage ?

i just wonder,
i found trouble using non ascii chars in the zipEntry filenames...
so i opened up the source code i found that you are encoding the filenames by using
ZipConstants.DefaultCodePage why using CodePage and not Encoding.UTF-8?

Unity-Windows Phone 8 Compatibility Issue

Hello,

I was trying to use SharpZipLib dlls in my project. Using the Dll in 'net-11' & 'net-20' folder results in the following error.
Exception: Error: type System.Runtime.Serialization.SerializationInfo doesn't exist in target framework.

Using the Dll in 'netcf-20' gives me following error:
Exception: Error: method System.Text.Encoding System.Text.Encoding::get_ASCII() doesn't exist in target framework.

Please help me in figuring this out.

The code that I am using is:

using UnityEngine;
using System;
using System.Text;
using System.Collections;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

public class ZipTest : MonoBehaviour
{

private WWW www;
private bool isUnzipped = false;

void Start()
{
    string url = "http://www.example.com/example.zip";
    www = new WWW(url);
}

void Update()
{
    Debug.Log("Downloaded :"+www.progress * 100);
    if (www.isDone && !isUnzipped)
    {
        Debug.Log("Load of test.zip complete");
        byte[] data = www.bytes;

        string docPath = Application.persistentDataPath;
        docPath = docPath.Substring(0, docPath.Length - 5);
        docPath = docPath.Substring(0, docPath.LastIndexOf("/"));
        docPath += "/Example/Example.zip";
        Debug.Log("docPath=" + docPath);

      //  System.IO.File.WriteAllBytes(docPath, data);           // Not supported in WP8 platform

        using (FileStream fs = new FileStream(docPath, FileMode.Create))
        {
            using (BinaryWriter writer = new BinaryWriter(fs))
            {
                writer.Write(data);
                writer.Close();
            }
            fs.Close();
            fs.Dispose();
        }

        using (ZipInputStream s = new ZipInputStream(File.OpenRead(docPath)))
        {
            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                Console.WriteLine(theEntry.Name);

                string directoryName = Path.GetDirectoryName(theEntry.Name);
                string fileName = Path.GetFileName(theEntry.Name);

                // create directory
                if (directoryName.Length > 0)
                {
                    Directory.CreateDirectory(directoryName);
                }

                if (fileName != String.Empty)
                {
                    string filename = docPath.Substring(0, docPath.Length - 8);
                    filename += theEntry.Name;
                    Debug.Log("Unzipping: " + filename);
                    using (FileStream streamWriter = File.Create(filename))
                    {
                        int size = 2048;
                        byte[] fdata = new byte[2048];
                        while (true)
                        {
                            size = s.Read(fdata, 0, fdata.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(fdata, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            isUnzipped = true;
        }
    }
}

}

Does not extract folders correctly in OSX (Mono)

A zip file containing a single .bundle package (essentially a folder structure) when unzipped using Libraries.ICSharpCode.SharpZipLib.Zip.FastZip.ExtractZip extracts incorrectly in OSX, but works in Windows.

The resulting unzip extracts all files inside the .bundle package as files named for the folders they were in. For example, a .bundle containing 3 files which should be extracted to a single .bundle file will instead be extracted as follows:

name.bundle/Contents/MacOS/name
name.bundle/Contents/Resources/en.lproj/InfoPlist.strings
name.bundle/Contents/Info.plist

Keep in mind these are not folders being created -- its creating 3 files with the folder structure baked into their names.

I haven't tested a regular compressed folder, but .bundles are not being extracted correctly.

EDIT: Same problem happens with regular directories not in a bundle.

I've determined its because it's using "" for the directory separator char instead of Path.DirectorySeparatorChar throughout due to the processing by the WindowsNameTransform class.

Add file to Exists Zip file in windows phone

Hello,
i have a project Windows phone 8 and i must add a file into a exists zip file (created with sharpziplib).
I'm write this code but not it works

        public void CreateZip()
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isf.FileExists("CompressedFiles.zip")) isf.DeleteFile("CompressedFiles.zip");

                using (IsolatedStorageFileStream fsOut = new IsolatedStorageFileStream("CompressedFiles.zip", System.IO.FileMode.Create, isf))
                {
                     ZipOutputStream _zipStream;
                    _zipStream = new ZipOutputStream(fsOut);
                    _zipStream.SetLevel(7); 
                    _zipStream.Close();
                }
            }
        }
    private void AddFileToExistsZip(string path)
    {

        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
        {

            using (IsolatedStorageFileStream fsOut = new IsolatedStorageFileStream("CompressedFiles.zip", System.IO.FileMode.Append, isf))
            {
                ZipOutputStream zipStream = new ZipOutputStream(fsOut);

                string entryName;
                entryName = ZipEntry.CleanName(path); 
                ZipEntry newEntry = new ZipEntry(entryName);
                newEntry.DateTime = DateTime.Now;

                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, System.IO.FileMode.Open, isf))
                {
                    newEntry.Size = stream.Length;
                }

                zipStream.PutNextEntry(newEntry);

                byte[] buffer = new byte[4096];
                using (IsolatedStorageFileStream streamReader = isf.OpenFile(path, System.IO.FileMode.Open))
                {
                    StreamUtils.Copy(streamReader, zipStream, buffer);
                }
                zipStream.CloseEntry();
                zipStream.Finish();
                zipStream.Close();
            }
        }
    }

if i add a zip file have ONLY last file added Why?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.