ZIP file created with SharpZipLib cannot be opened on Mac OS X

前端 未结 10 1346
有刺的猬
有刺的猬 2021-02-04 08:31

Argh, today is the day of stupid problems and me being an idiot.

I have an application which creates a zip file containing some JPEGs from a certain directory. I use th

10条回答
  •  无人共我
    2021-02-04 09:21

    So, I searched for a few more examples on how to use SharpZipLib and I finally got it to work on Windows and os x. Basically I added the "Crc32" of the file to the zip archive. No idea what this is though.

    Here is the code that worked for me:

            using (var outStream = new FileStream("Out3.zip", FileMode.Create))
            {
                using (var zipStream = new ZipOutputStream(outStream))
                {
                    Crc32 crc = new Crc32();
    
                    foreach (string pathname in pathnames)
                    {
                        byte[] buffer = File.ReadAllBytes(pathname);
    
                        ZipEntry entry = new ZipEntry(Path.GetFileName(pathname));
                        entry.DateTime = now;
                        entry.Size = buffer.Length;
    
                        crc.Reset();
                        crc.Update(buffer);
    
                        entry.Crc = crc.Value;
    
                        zipStream.PutNextEntry(entry);
                        zipStream.Write(buffer, 0, buffer.Length);
                    }
    
                    zipStream.Finish();
    
                    // I dont think this is required at all
                    zipStream.Flush();
                    zipStream.Close();
    
                }
            }
    

    Explanation from cheeso:

    CRC is Cyclic Redundancy Check - it's a checksum on the entry data. Normally the header for each entry in a zip file contains a bunch of metadata, including some things that cannot be known until all the entry data has been streamed - CRC, Uncompressed size, and compressed size. When generating a zipfile through a streamed output, the zip spec allows setting a bit (bit 3) to specify that these three data fields will immediately follow the entry data.

    If you use ZipOutputStream, normally as you write the entry data, it is compressed and a CRC is calculated, and the 3 data fields are written immediately after the file data.

    What you've done is streamed the data twice - the first time implicitly as you calculate the CRC on the file before writing it. If my theory is correct, the what is happening is this: When you provide the CRC to the zipStream before writing the file data, this allows the CRC to appear in its normal place in the entry header, which keeps OSX happy. I'm not sure what happens to the other two quantities (compressed and uncompressed size).


提交回复
热议问题