在Xamarin Forms Android中创建Zip文件

4
我想在Xamarin Forms跨平台中创建一个Zip文件。 我为每个平台使用自定义方法,包括iOS和Android。 在iOS上,我使用ZipArchive库实现了这个目标,但是我没有找到Android的替代品。 所以,我尝试原生方式来创建(只有一个文件的)Zip文件,但是它创建的Zip文件是空的。
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 和 zos 应该被释放,不知道这是否会解决你的问题。 - Leo Nix
你是对的!需要关闭ZOS并释放FOS。 - jpintor
我已将您的评论和解决方案移动到社区维基页面。 - Cœur
2个回答

1
< p > < em > Leo Nix和OP提供的解决方案。

需要关闭ZOS。
fos和zos应该被处理。

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

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

1

我注意到提问和解决方案代码不完整。我不得不更改一些内容使其正常工作,所以这里是完整的代码:

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

我希望它有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接