Create Zip file in Xamarin Forms Android

I want to create a zip file in the Xamarin Forms Cross Platform. I use an individual approach for each platform, iOS and Android. On iOS, it works with the ZipArchive library, but I did not find an alternative for Android.

So I try to do this native (to create a 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();
}
+4
source share
2 answers

Solution from Leo Nix and OP.

You must close ZOS.
fos and zos should be removed.

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

  zos.Dispose();
  fos.Dispose();
}
+1
source

I noticed that the request and solution code was not complete. I had to change something to make it work, here is the full 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();
    }
}

Hope this helps.

+1

Source: https://habr.com/ru/post/1612935/


All Articles