zipstorer icon indicating copy to clipboard operation
zipstorer copied to clipboard

Reading an archive content and then adding no files to it causes archive corruption

Open xtomino opened this issue 6 years ago • 2 comments

Thank you very much for developing ZipStorer. I have used it in several apps and until now I haven't encountered a problem.

In my last project I needed check a content of archive before add new files to avoid duplicate file names in that archive. I find out if I read an archive content and then I add no files into it to avoid duplicates causes an archive corruption.

See my test code. After first run a new archive is created. After second run an existing archive is opened and after check for duplicate file names in archive no files are added. And after that the whole archive is corrupted! And I opened only an existing archive, then I read its content, I wrote down no files and in the end I close it.

Do you have an idea where the problem might be?

const string archiveFilePath = @"C:\Temp\test.zip";
var archiveFileExists = File.Exists(archiveFilePath);
using (var zipArchive = archiveFileExists
  ? ZipStorer.Open(archiveFilePath, FileAccess.ReadWrite)
  : ZipStorer.Create(archiveFilePath, "TestArchive"))
{
  var zipFileEntries = archiveFileExists
    ? zipArchive.ReadCentralDir()
    : new List<ZipStorer.ZipFileEntry>();
  for (int i = 0; i < 10; i++)
  {
    if (zipFileEntries.Any(e => e.FilenameInZip == $"TestFile_{i + 1:00}.txt")) continue;
    using (var memoryStream = new MemoryStream())
    using (var streamWriter = new StreamWriter(memoryStream))
    {
      streamWriter.WriteLine("TEST!");
      streamWriter.Flush();
      memoryStream.Seek(0, SeekOrigin.Begin);
      zipArchive.AddStream(ZipStorer.Compression.Deflate, $"TestFile_{i + 1:00}.txt", memoryStream, 
      DateTime.Now, string.Empty);
    }
  }
}

xtomino avatar Oct 01 '17 18:10 xtomino

Hi xtomino, Please try with the following: At the beginning of the Close() method add the following code:

if (Files.Count == 0)
      return;

Let me know if it works

jaime-olivares avatar Feb 04 '18 20:02 jaime-olivares

Hi jaime-olivares,

I have tried it and I can confirm that it works. BUT it was expected, because the ZIP file remained intact ;-) Unfortunately, I found an another bug. I have used the same code snippet.

Steps to reproduce:

  1. run code for the first time
  2. with external tool delete any file from test.zip archive
  3. run code for the second time
  4. with external tool open test.zip and the last file in the archive will be corrupted (bad CRC)!!!

xtomino avatar Feb 16 '18 13:02 xtomino