How do I zip files in Xamarin for Android?

元气小坏坏 提交于 2019-12-05 19:48:16

Using Read() on a FileStream returns the amount of bytes read into the stream or 0 if the end of the stream has been reached. It will never return a value of -1.

From MSDN:

The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, orzero if the end of the stream is reached.

I'd modify your code to the following:

System.IO.FileStream fos = new System.IO.FileStream(sZipToDirectory + sZipFileName, FileMode.Create);
Java.Util.Zip.ZipOutputStream zos = new Java.Util.Zip.ZipOutputStream(fos);

byte[] buffer = new byte[1024];
for (int i = 0; i < arrFiles.Length; i++) {

    FileInfo fi = new FileInfo (arrFiles[i]);
    Java.IO.FileInputStream fis = new Java.IO.FileInputStream(fi.FullName);

    ZipEntry entry = new ZipEntry(arrFiles[i].Substring(arrFiles[i].LastIndexOf("/") + 1));
    zos.PutNextEntry(entry);

    int count = 0;
    while ((count = fis.Read(buffer)) > 0) {
        zos.Write(buffer, 0, count);
    }

    fis.Close();
    zos.CloseEntry();
}

This is nearly identical to the code I've used for creating zip archives on Android in the past.

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();

Are you allowed to use SharpZip? It's really easy to use.

Here is a blog post I wrote to extract zip files

    private static void upzip(string url)
    {
        WebClient wc = new WebClient();
        wc.DownloadFile(url, "temp.zip");  
        //unzip
        ZipFile zf = null;
        try
        {
            zf = new ZipFile(File.OpenRead("temp.zip"));
            foreach (ZipEntry zipEntry in zf)
            {
                string fileName = zipEntry.Name;
                byte[] buffer = new byte[4096];
                Stream zipStream = zf.GetInputStream(zipEntry);
                using (FileStream streamWriter = File.Create( fileName))
                {
                    StreamUtils.Copy(zipStream, streamWriter, buffer);
                }
            }

        }
        finally
        {
            if (zf != null)
            {
                zf.IsStreamOwner = true;
                zf.Close();
            }
        }

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!