Search code examples
c#.netzipsharpziplibicsharpcode

ICSharpCode.SharpZipLib.Zip Create zip with directory entry throws "Entry cannot have any data"


I have a problem creating an archive and adding a directory entry. My code looks as follows:

using (var zip = ZipFile.Create(zipPath))
{
    if (!string.IsNullOrEmpty(password))
    {
        zip.ZipCryptoEncoding = Encoding.UTF8;
        zip.Password = password;
    }
    zip.UseZip64 = UseZip64.Dynamic;

    var EntryFactory = new ZipEntryFactory();
    ZipEntry dirEntry = EntryFactory.MakeDirectoryEntry(dirPath);
    dirEntry.DateTime = DateTime.Now;
    dirEntry.IsUnicodeText = true;

    if (!string.IsNullOrEmpty(password))
    {
        dirEntry.AESKeySize = 256;
    }
    if (!compression)
    {
        dirEntry.CompressionMethod = CompressionMethod.Stored;
    }
    if (compression)
    {
        dirEntry.CompressionMethod = CompressionMethod.Deflated;
    }
    zip.BeginUpdate();
    zip.Add(dirEntry);
    zip.CommitUpdate();
}

It throws an exception "Entry cannot have any data." Is there a way to add directory entry to a zip file?


Solution

  • IMO this is a bug in SharpZipLib.

    ZipFile.Add(ZipEntry) checks if both ZipEntry.Size and ZipEntry.CompressedSize are not 0, however, their default values are -1, and ZipEntryFactory.MakeDirectoryEntry only initializes the Size property to 0.

    So you need to do:

    dirEntry.CompressedSize = 0L;