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

Archive Multiple Files In Zip & Extract Zip Archive

, 14 Oct 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Learn how to create zip archive and extract it without any 3rd party library

Introduction

Here, I am presenting one more tip regarding archiving files as ZIP and extracting it. ZIP is a well known format for archiving a bunch of files for sharing purposes.

Background

Me and my colleagues were developing an app and one of my colleagues asked me how I could 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 to Zip and Unzip archives in Windows Store Apps developed by C#/XAML.

Using the Code

System.IO.Compression namespace provides methods to zip and unzip files. For creating zip file, that namespace provides 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 byte[] array. So here's the 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?

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 our zip files. Now we have to read the content of that archive, so basically they are a collection of ZipArchiveEntry. So we will read 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 the 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)

Share

About the Author

Farhan Ghumra
Software Developer (Senior) Simform Solutions Pvt. Ltd.
India India
Windows Metro Store Apps Developer having 1+ year of experience
 
Follow me on: My Blog on Windows 8 | Twitter | Facebook | LinkedIn
 
Check Out My Articles & Tips on CodeProject
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralWell written Pinmemberchaz-chance15-Oct-13 10:48 
GeneralRe: Well written PinmemberFarhan Ghumra15-Oct-13 16:17 
SuggestionPlease move to .Net Framework PinmemberL. Braun14-Oct-13 6:58 
GeneralRe: Please move to .Net Framework PinmemberFarhan Ghumra14-Oct-13 7:51 
GeneralMy vote of 1 Pinmemberrodrigo.ratan11-Oct-13 21:30 
GeneralRe: My vote of 1 PinmemberFarhan Ghumra11-Oct-13 22:11 
GeneralRe: My vote of 1 Pinmemberrodrigo.ratan6-Nov-13 10:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141216.1 | Last Updated 14 Oct 2013
Article Copyright 2013 by Farhan Ghumra
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid