在Xamarin表单Android中创建Zip文件
我想在Xamarin表单跨平台中创建一个zip文件。 我对每一个平台,iOS和Android都使用一种定制的方式。 在iOS中,ZipArchive与库一起工作,但我找不到Android的替代品 因此,我尝试使用本机方式(仅使用一个文件创建zip),但zip文件是空的在Xamarin表单Android中创建Zip文件,android,xamarin,xamarin.forms,zip,Android,Xamarin,Xamarin.forms,Zip,我想在Xamarin表单跨平台中创建一个zip文件。 我对每一个平台,iOS和Android都使用一种定制的方式。 在iOS中,ZipArchive与库一起工作,但我找不到Android的替代品 因此,我尝试使用本机方式(仅使用一个文件创建zip),但zip文件是空的 public void Compress(string path, string filename, string zipname) { var personalpath = Environment.GetFolderPath
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();
}
Leo Nix和OP提出的解决方案
需要关闭ZOS。应处置fos和ZO
...
zos.CloseEntry();
zos.Close();
zos.Dispose();
fos.Dispose();
}
我注意到询问和解决方案代码不完整。我必须更改一些东西才能使其正常工作,下面是完整的代码:
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();
}
}
我希望它能有所帮助。fos和zos应该被处理掉。不知道这是否能解决你的问题。你是对的!需要关闭ZOS并进行处置,因为我已将您的评论和解决方案移动到社区wiki。