Click here to Skip to main content
Click here to Skip to main content

Archive Multiple Files In Zip & Extract Zip Archive

By , 8 Feb 2013
 

Introduction 

Here I am presenting one more article regarding archiving files as ZIP and extracting it. ZIP is well known format for archiving bunch of files for sharing purpose.

Background 

Me and my colleagues were developing an app and one of my colleague asked me that how can I create a ZIP file ? So I searched on MSDN, but didn't find any good example. So I thought it would be great if I write a simple article for that. Here I present you the way how to Zip and Unzip archives in Windows Store Apps developed by C#/XAML 

Using the code 

System.IO.Compression name space provides methods to zip and unzip files. For creating zip file that name space provide ZipArchive class. That represents a zip file. Now it's time to insert files, so we can use FileOpenPicker to pick files and to add files in archive, we will use ZipArchiveEntry class. 

ZipArchiveEntry represents each file to be added in Zip archive. We have to writes bytes of file in ZipArchiveEntry, hence I used a helper method GetByteFromFile(), which takes  StorageFile object and returns me byte[] array. So here's code for zipping the files. 

private async void ZipClick(object sender, RoutedEventArgs e)
{
    FileSavePicker picker = new FileSavePicker();
    picker.FileTypeChoices.Add("Zip Files (*.zip)", new List<string> { ".zip" });
    picker.SuggestedStartLocation = PickerLocationId.Desktop;
    picker.SuggestedFileName = "1";
    zipFile = await picker.PickSaveFileAsync();

    using (var zipStream = await zipFile.OpenStreamForWriteAsync())
    {
        using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create))
        {
            foreach (var file in storeFile)
            {
                ZipArchiveEntry entry = zip.CreateEntry(file.Name);

                using (Stream ZipFile = entry.Open())
                {
                    byte[] data = await GetByteFromFile(file);
                    ZipFile.Write(data, 0, data.Length);
                }
            }
        }
    }
}
// This is the method to convert the StorageFile to a Byte[]       
private async Task<byte[]> GetByteFromFile(StorageFile storageFile)
{
    var stream = await storageFile.OpenReadAsync();

    using (var dataReader = new DataReader(stream))
    {
        var bytes = new byte[stream.Size];
        await dataReader.LoadAsync((uint)stream.Size);
        dataReader.ReadBytes(bytes);

        return bytes;
    }
}
storeFile is the list of StorageFile objects. Isn't it simple, no ? 

Now it's time to unzip the archived file. It's also quite simple. First of all select the location to which you want to extract archive then create object of ZipArchive class which represents the our zip files. Now we have to read the content of that archive, so basically  they are  collection of ZipArchiveEntry. So we will read the each entry and obviously they will be in byte[] array, so we will generate stream from that and finally we will get whole files from archive. Here's unzipping code. 

private async void UnZipClick(object sender, RoutedEventArgs e)
{
    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
    openPicker.FileTypeFilter.Add(".zip");
    StorageFile file = await openPicker.PickSingleFileAsync();
    FolderPicker folderPicker = new FolderPicker();
    folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
    folderPicker.FileTypeFilter.Add("*");
    StorageFolder destinationFolder = await folderPicker.PickSingleFolderAsync();
    Stream zipMemoryStream = await file.OpenStreamForReadAsync();
    // Create zip archive to access compressed files in memory stream
    using (ZipArchive zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Read))
    {
        // For each compressed file...
        foreach (ZipArchiveEntry entry in zipArchive.Entries)
        {
            // ... read its uncompressed contents
            using (Stream entryStream = entry.Open())
            {
                byte[] buffer = new byte[entry.Length];
                entryStream.Read(buffer, 0, buffer.Length);
                try
                {
                    //Create a file to store the contents
                    StorageFile uncompressedFile = await destinationFolder.CreateFileAsync(entry.Name, CreationCollisionOption.ReplaceExisting);
                    // Store the contents
                    using (IRandomAccessStream uncompressedFileStream = await uncompressedFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        using (Stream outstream = uncompressedFileStream.AsStreamForWrite())
                        {
                            outstream.Write(buffer, 0, buffer.Length);
                            outstream.Flush();
                        }
                    }
                }
                catch
                {
                }
            }
        }
    }
} 
Points of Interest

The point of interest is that you don't need to use 3rd party DLLs for archiving files. This is basic Zipping and Unzipping file tutorial. If you need further operation kindly check  MSDN documents and let me know what new thing you learnt. Thanks.  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Farhan Ghumra
Software Developer Simform Solutions Pvt. Ltd.
India India
Member
Windows Metro Store Apps Developer
 
Follow me on: My Blog on Windows 8 | Twitter | Facebook | LinkedIn
 
Check Out My Articles & Tips

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 8 Feb 2013
Article Copyright 2013 by Farhan Ghumra
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid