0
votes

We have ZipFile class in Xamarin forms android to zip a file, is there a way to use the same in xamarin forms iOS project. I do not want to use third party libraries like "ICSharpCode.SharpZipLib.Zip" which sometimes takes 10 minutes to compress a file and causes some other problems.

I also tried GZipStream, which does not give desired results. It is difficult to extract after downloading with this extension.

Thanks.

2

2 Answers

1
votes

The iOS/MacOS Compression Framework would be the fastest and cause no additional bloat

re: https://developer.apple.com/documentation/compression?language=objc

While it does not support creating a "Zip"-based internally formatted file, it does support multiple compression algorithms.

Apple recommends using COMPRESSION_ZLIB:

The zlib compression algorithm, recommended for cross-platform compression.

There are a multitude of (de)compression tools on that can decompress zlib raw based files, but to make it "easier", you can include a header so gzip (Windows, macOS, and Linux) can handle them without further changes. (You can also add a CRC-based footer to the file, but it is not really needed, unless you are comparing the mobile and server CRCs of your zip files already...)

Raw zlib w/header Example:

using (var fileOriginal = new FileStream(inputFile, FileMode.Open))
using (var fileCompressed = new FileStream(outputZip, FileMode.Create))
using (var compressionStream = new Compression.CompressionStream(fileCompressed, System.IO.Compression.CompressionMode.Compress, CompressionAlgorithm.Zlib, true))
{
    var header = new byte[] { 31, 139, 8, 0, 0, 0, 0, 0, 0, 0 }; // \x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00
    fileCompressed.Write(header, 0, header.Length);

    fileOriginal.CopyTo(compressionStream);
}
0
votes

You can use ZipFile.CreateFromDirectory from System.IO.Compression in your shared project to compress the file. Sample usage will be like ZipFile.CreateFromDirectory(folderPath, Path.Combine(storagePath, zipFileName));