c#实现metro文件压缩解压示例

时间:2021-05-20

在1.zip中增加一张新图片
复制代码 代码如下:
StorageFile jpg = await KnownFolders.PicturesLibrary.GetFileAsync("1.jpg");
StorageFile zip = await KnownFolders.PicturesLibrary.GetFileAsync("1.zip");

//把上面这句改成如下就成了压缩文件
//StorageFile zip = await KnownFolders.PicturesLibrary.CreateFileAsync(jpg.DisplayName+".zip",CreationCollisionOption.ReplaceExisting);
  
  
using (ZipArchive archive = new ZipArchive((await zip.OpenAsync(FileAccessMode.ReadWrite)).AsStream(), ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = archive.CreateEntry(jpg.Name);
byte[] buffer = WindowsRuntimeBufferExtensions.ToArray(await FileIO.ReadBufferAsync(jpg));
using (var writer = readmeEntry.Open())
{
await writer.WriteAsync(buffer, 0, buffer.Length);
}
}

把1.jpg从1.zip中删除
复制代码 代码如下:
StorageFile zip = await KnownFolders.PicturesLibrary.GetFileAsync("1.zip");
using (ZipArchive archive = new ZipArchive((await zip.OpenAsync(FileAccessMode.ReadWrite)).AsStream(), ZipArchiveMode.Update))
{
//删除文件
archive.GetEntry("1.jpg").Delete();
}

导出1.jpg,newFile为要到出的文件
复制代码 代码如下:
StorageFile zip = await KnownFolders.PicturesLibrary.GetFileAsync("1.zip");
using (ZipArchive archive = new ZipArchive((await zip.OpenAsync(FileAccessMode.ReadWrite)).AsStream(), ZipArchiveMode.Update))
{
            ZipArchiveEntry zipArchiveEntry = archive.GetEntry("1.jpg").
            using (Stream fileData = zipArchiveEntry.Open())
{
StorageFile newFile = await KnownFolders.PicturesLibrary.CreateFileAsync(zipArchiveEntry.FullName, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream newFileStream = await newFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (Stream s = newFileStream.AsStreamForWrite())
{
await fileData.CopyToAsync(s);
await s.FlushAsync();
}
}
}
      }

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章