Some applications need to deploy databases or data files to user’s system. These files may be zipped to reduce package size and to improve speed of installation. For example, the following screenshot demonstrates Demo.zip archive added to Windows Store app:
.NET Framework 4.5 provides native support for zip files with help of two new classes – ZipFile
and ZipArchive
, both located in System.IO.Compression
namespace. ZipFile
includes two convenient functions - CreateFromDirectory()
and ExractToDirectory()
and allows to create an archive or extract all files in one method call. ZipArchive
methods are more verbose but provide more granular access to zipped files.
Unfortunately, ZipFile
is not included in .NET profile for Windows Store, probably because of its synchronous nature, thus ZipArchive
is the only class to handle zip files.
The following snippet demonstrates opening of deployed archive and extracting of files to app’s local data folder:
private async static Task<List<StorageFile>> UnZip()
{
var files = new List();
// open zip
var zipFile = await Package.Current.InstalledLocation.GetFileAsync("Data.zip");
using (var zipStream = await zipFile.OpenReadAsync())
{
using (var archive = new ZipArchive(zipStream.AsStream()))
{
// iterate through zipped objects
foreach (var archiveEntry in archive.Entries)
{
using (var outStream = archiveEntry.Open())
{
// unzip file to app's LocalFolder
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(archiveEntry.Name);
using (var inStream = await file.OpenStreamForWriteAsync())
{
await outStream.CopyToAsync(inStream);
}
files.Add(file);
}
}
}
}
// return list of unzipped files
return files;
}
This method works perfectly with flat archives, when all files are located in the root of .zip file. For non-flat archives, the method can be modified to detect folders by empty archiveEntry.Name
property. Additionally, archiveEntry.FullName
provides relative file path and helps to arrange files according to original archive structure.