c# sharpziplib adding file to existing archive

Grant picture Grant · Aug 31, 2009 · Viewed 15.7k times · Source

am trying to add a file to an existing archive using the following code. When run no errors or exceptions are shown but no files are added to the archive either. Any ideas why?

        using (FileStream fileStream = File.Open(archivePath, FileMode.Open, FileAccess.ReadWrite))
        using (ZipOutputStream zipToWrite = new ZipOutputStream(fileStream))
        {
            zipToWrite.SetLevel(9);

            using (FileStream newFileStream = File.OpenRead(sourceFiles[0]))
            {
                byte[] byteBuffer = new byte[newFileStream.Length - 1];

                newFileStream.Read(byteBuffer, 0, byteBuffer.Length);

                ZipEntry entry = new ZipEntry(sourceFiles[0]);
                zipToWrite.PutNextEntry(entry);
                zipToWrite.Write(byteBuffer, 0, byteBuffer.Length);
                zipToWrite.CloseEntry();

                zipToWrite.Close();
                zipToWrite.Finish();
            }
        }

Answer

Cheeso picture Cheeso · Oct 24, 2009

In DotNetZip, adding files to an existing zip is really simple and reliable.

using (var zip = ZipFile.Read(nameOfExistingZip))
{
    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
    zip.AddFile(additionalFileToAdd);
    zip.Save();
}

If you want to specify a directory path for that new file, then use a different overload for AddFile().

using (var zip = ZipFile.Read(nameOfExistingZip))
{
    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
    zip.AddFile(additionalFileToAdd, "directory\\For\\The\\Added\\File");
    zip.Save();
}

If you want to add a set of files, use AddFiles().

using (var zip = ZipFile.Read(nameOfExistingZip))
{
    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
    zip.AddFiles(listOfFilesToAdd, "directory\\For\\The\\Added\\Files");
    zip.Save();
}

You don't have to worry about Close(), CloseEntry(), CommitUpdate(), Finish() or any of that other gunk.