Search code examples
c#.net-4.5dotnetzip

Add multiple files to archive


I have no idea why this won't work - starting to drive me crazy!

Nobody else seems to have this problem

My code looks something like this:

        Stream stream = new MemoryStream();
        try
        {
            // output zip
            using (ZipFile zipFile = new ZipFile())
            {
                zipFile.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                ForEach(DataFile file In DataFiles)
                {
                    String sourcePath = dataFile.Path;
                    String archiveName = dataFile.RealName;
                    //byte[] fileContents = File.ReadAllBytes(sourcePath);
                    //zipFile.AddEntry(archiveName, fileContents);
                    zipFile.AddFile(sourcePath, archiveName);
                    //e.FileName = archiveName;
                }

                zipFile.AddEntry("README.TXT", readmeMessage);
                zipFile.Save(stream);
            }
        }
        catch (Exception ex)
        {
            throw;
        }

All the file paths are valid.

Adding the readme file works fine, if I comment out the rest. But adding the other files causes the zip file to be invalid.

I would appreciate any suggestions!

Thanks

UPDATE

I've noticed that if I initialise the stream with exactly the right size it works. Does anyone know how to get the size of the archive without writing it to disk?

FURTHER UPDATE

I've added a workaround for now.

I can do what I need to by saving the archive to disk then reading it back into another stream

Very lame and I really don't like it, so if anyone can suggest a better way I'd be grateful!


Solution

  • It seems that once the zip archive reaches a certain size (I haven't tested enough to be sure of the actual limit) it cannot be reliably saved to a stream.

    Although nobody seems to be saying it, the only way around this is to save the archive to disk.