我在尝试实现SharpZipLib.Portable 时到了这里。
我开始在没有 IVirtualFileSystem 的情况下使用它,因为我已经有一个名为 (PCLStorage) 的库,它知道如何在文件系统中读写(在 iOS 和 Android 上进行了测试)。
注意:这些实现都在针对iOS、Android 的PCL 中。无需针对 Android 或 iOS 的特定代码。
这里是一个简单的例子,如何使用PCLStorage 和SharpZipLib.Portable 提取一个 Zip 文件:
public async void DonwLoadAndStoreZipFile()
{
var bytes = await DownloadImageAsync("https://github.com/fluidicon.png");
// IFolder interface comes from PCLStorage
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder = await rootFolder.CreateFolderAsync("zipFolder", CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("test.zip" , CreationCollisionOption.OpenIfExists);
using (Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
await stream.WriteAsync(bytes, 0, bytes.Length);
using (var zf = new ZipFile(stream))
{
foreach (ZipEntry zipEntry in zf)
{
// Gete Entry Stream.
Stream zipEntryStream = zf.GetInputStream(zipEntry);
// Create the file in filesystem and copy entry stream to it.
IFile zipEntryFile = await rootFolder.CreateFileAsync(zipEntry.Name , CreationCollisionOption.FailIfExists);
using(Stream outPutFileStream = await zipEntryFile.OpenAsync(FileAccess.ReadAndWrite))
{
await zipEntryStream.CopyToAsync(outPutFileStream);
}
}
}
}
}
如果你想获得一些关于如何使用SharpZipLib.Portable 的例子,你可以在这里阅读(原文SharpZipLib):
Code reference
和
Zip samples.
替代方案:
完成我上面解释的操作后,我得到了一个更简单的解决方案,因为我只需要支持 ZIP 文件。
我在System.IO.Compression 和PCLStorage 中使用了ZipArchive Class,所以在这个解决方案中我没有使用SharpZipLib.Portable。
这是版本:
public async void DonwLoadAndStoreZipFile()
{
var bytes = await DownloadImageAsync(https://github.com/fluidicon.png);
// IFolder interface comes from PCLStorage
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder = await rootFolder.CreateFolderAsync("zipFolder", CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("test.zip" , CreationCollisionOption.OpenIfExists);
using (Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
await stream.WriteAsync(bytes, 0, bytes.Length);
using(ZipArchive archive = new ZipArchive(stream))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
IFile zipEntryFile = await rootFolder.CreateFileAsync(entry.Name, CreationCollisionOption.FailIfExists);
using (Stream outPutStream = await zipEntryFile.OpenAsync(FileAccess.ReadAndWrite))
{
await entry.Open().CopyToAsync(outPutStream);
}
}
}
}
}