Search code examples
c#androidxamarinzipfilestream

How do I zip files in Xamarin for Android?


I have a function that creates a zip file a string array of files passed. The function does succeed in creating the zip file and the zip entry files inside it, but these zip entry files are empty. I've tried a couple of different methods - the function code below is the closest I've gotten to something working:

    public static bool ZipFile(string[] arrFiles, string sZipToDirectory, string sZipFileName)
    {
        if (Directory.Exists(sZipToDirectory))
        {
            FileStream fNewZipFileStream;
            ZipOutputStream zos;

            try {
                fNewZipFileStream = File.Create(sZipToDirectory + sZipFileName);
                zos = new ZipOutputStream(fNewZipFileStream);

                for (int i = 0; i < arrFiles.Length; i++) {
                    ZipEntry entry = new ZipEntry(arrFiles[i].Substring(arrFiles[i].LastIndexOf("/") + 1));
                    zos.PutNextEntry(entry);

                    FileStream fStream = File.OpenRead(arrFiles[i]);
                    BufferedStream bfStrm = new BufferedStream(fStream);

                    byte[] buffer = new byte[bfStrm.Length];
                    int count;
                    while ((count = bfStrm.Read(buffer, 0, 1024)) != -1) {
                        zos.Write(buffer);
                    }

                    bfStrm.Close();
                    fStream.Close();
                    zos.CloseEntry();
                }
                zos.Close();
                fNewZipFileStream.Close();
                return true;
            }
            catch (Exception ex)
            {
                string sErr = ex.Message;
                return false;
            }
            finally
            {
                fNewZipFileStream = null;
                zos = null;
            }
        }
        else
        {
            return false;
        }
    }

I think it's got to do with the byte stream handling. I've tried this bit of code that handles the stream but it goes into an infinite loop:

while ((count = fStream.Read(buffer, 0, 1024)) != -1) {
        zos.Write(buffer, 0, count);
}
fStream.Close();

Solution

  • I found a solution that is quite simple - I used the ReadAllBytes method of the static File class.

    ZipEntry entry = new ZipEntry(arrFiles[i].Substring(arrFiles[i].LastIndexOf("/") + 1));
    zos.PutNextEntry(entry);
    
    byte[] fileContents = File.ReadAllBytes(arrFiles[i]);
    zos.Write(fileContents);
    zos.CloseEntry();