在开发一个Win8 Modern UI APP时,如果需要用到ZIP压缩和解压文件(注意不是GZIP),可能会首先想到使用SharpZipLib,由于我们在WP7的时候就使用的这个类库。不过,随着WIN8开始使用.Net 4.5和C# 5.0,引入了一个新功能,其实ZIP压缩与解压缩已经可以不用第三方类库就能实现了。
主要需要用到System.IO.Compression命名空间。下面演示程序需要用到的全部命名空间如下:
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Streams;
对zip文件的解压缩操作:
public async Task<StorageFolder> UnZipFile(string folderName, byte[] data) { StorageFolder unZipfolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists); var stream = new MemoryStream(data); var zipArchive = new ZipArchive(stream, ZipArchiveMode.Read); foreach (var zipArchiveEntry in zipArchive.Entries) { if (!String.IsNullOrEmpty(zipArchiveEntry.FullName)) { if (!zipArchiveEntry.FullName.EndsWith("/")) { string fileName = zipArchiveEntry.FullName.Replace("/", "\\"); using (Stream fileData = zipArchiveEntry.Open()) { StorageFile newFile = await unZipfolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream newFileStream = await newFile.OpenAsync(FileAccessMode.ReadWrite)) { using (Stream s = newFileStream.AsStreamForWrite()) { await fileData.CopyToAsync(s); await s.FlushAsync(); s.Dispose(); } newFileStream.Dispose(); } } } } } return unZipfolder; }
UnZipFile()方法,传入的第一个参数为欲解压的文件位置(解压缩位置LocalFolder中新建一个文件夹,可以根据实际需求进行修改),第二个参数为压缩文件的字节数组,这个数组可能来源于网络下载或者其他独立存储空间中的文件。
对文件夹的压缩(如果需要压缩单个文件,代码可从下面的代码中提取):
public async Task<byte[]> ZipFolder(StorageFolder folder) { using (var zipMemoryStream = new MemoryStream()) { using (var zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Create)) { await AddZipFolderToEntry(zipArchive, folder, ""); } return zipMemoryStream.ToArray(); } } private async Task<bool> AddZipFolderToEntry(ZipArchive zipArchive, StorageFolder folder, string entryFirst) { IReadOnlyList<StorageFile> filesToCompress = await folder.GetFilesAsync(); foreach (StorageFile fileToCompress in filesToCompress) { byte[] buffer = (await FileIO.ReadBufferAsync(fileToCompress)).ToArray(); ZipArchiveEntry entry = zipArchive.CreateEntry(entryFirst + fileToCompress.Name); using (Stream entryStream = entry.Open()) { await entryStream.WriteAsync(buffer, 0, buffer.Length); } } var childrenFolder = await folder.GetFoldersAsync(); foreach (var storageFolder in childrenFolder) { await AddZipFolderToEntry(zipArchive, storageFolder, entryFirst + storageFolder.Name + "/"); } return true; }
ZipFolder()方法为将一个文件夹极其子文件夹与文件压缩成一个ZIP文件,具体过程为递归调用AddZipFolderToEntry。