4
votes

I want to create a zip file in Xamarin Forms Cross Platform. I use a custom way for every platform, iOS and Android. In iOS works with the Library ZipArchive, but I not found alternative for Android.

So I try do it native (to create zip with only one file), but the zip file was created empty.

public void Compress(string path, string filename, string zipname)
{
  var personalpath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  string folder = Path.Combine(personalpath, path);
  string zippath = Path.Combine(folder, zipname);
  string filepath = Path.Combine(folder, filename);

  System.IO.FileStream fos = new System.IO.FileStream(zippath, FileMode.OpenOrCreate);
  Java.Util.Zip.ZipOutputStream zos = new Java.Util.Zip.ZipOutputStream(fos);

  ZipEntry entry = new ZipEntry(filename.Substring(filename.LastIndexOf("/") + 1));
  byte[] fileContents = File.ReadAllBytes(filepath);
  zos.Write(fileContents);
  zos.CloseEntry();
}
2
fos and zos should be disposed. don't know if this will fix your problem or not. - Leo Nix
you are right! need to close ZOS and dispose FOS - jpintor
I've moved your comment and solution to a community wiki. - Cœur

2 Answers

1
votes

Solution by Leo Nix and OP.

Need to close ZOS.
fos and zos should be disposed.

  ...
  zos.CloseEntry();
  zos.Close();

  zos.Dispose();
  fos.Dispose();
}
1
votes

I've noticed the ask and solution code wasn't complete. I had to change somethings to make it work, so here is the complete code:

public void ZipFile(string fullZipFileName, params string[] fullFileName)
{
    using (FileStream fs = new FileStream(fullZipFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        using (ZipOutputStream zs = new ZipOutputStream(fs))
        {
            foreach (var file in fullFileName)
            {
                string fileName = Path.GetFileName(file);

                ZipEntry zipEntry = new ZipEntry(fileName);
                zs.PutNextEntry(zipEntry);
                byte[] fileContent = System.IO.File.ReadAllBytes(file);
                zs.Write(fileContent);
                zs.CloseEntry();
            }

            zs.Close();
        }
        fs.Close();
    }
}

I hope it help.