Click here to Skip to main content
15,884,628 members
Articles / Programming Languages / C#
Tip/Trick

Archive Multiple Files In Zip & Extract Zip Archive

Rate me:
Please Sign up or sign in to vote.
4.62/5 (9 votes)
14 Oct 2013CPOL2 min read 60.6K   1.4K   24   8
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.

C#
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);
                }
            }
        }
    }
}
C#
// 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.

C#
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)


Written By
Technical Lead eInfochips (An Arrow Company)
India India
Leading a passionate team to build metadata driven generic IoT Platform using for the operating companies (OpCos) of a Fortune 500 American conglomerate manufacturer of industrial products having annual revenue over $7 billion. Willing to join product-based and SaaS companies having production workloads and serving end customers happily.

Comments and Discussions

 
Generalgood example Pin
yolki201221-Sep-15 0:11
yolki201221-Sep-15 0:11 
GeneralWell written Pin
chaz-chance15-Oct-13 9:48
chaz-chance15-Oct-13 9:48 
GeneralRe: Well written Pin
Farhan Ghumra15-Oct-13 15:17
professionalFarhan Ghumra15-Oct-13 15:17 
SuggestionPlease move to .Net Framework Pin
L. Braun14-Oct-13 5:58
L. Braun14-Oct-13 5:58 
GeneralRe: Please move to .Net Framework Pin
Farhan Ghumra14-Oct-13 6:51
professionalFarhan Ghumra14-Oct-13 6:51 
GeneralMy vote of 1 Pin
Rodrigo Ratan [R2]11-Oct-13 20:30
Rodrigo Ratan [R2]11-Oct-13 20:30 
GeneralRe: My vote of 1 Pin
Farhan Ghumra11-Oct-13 21:11
professionalFarhan Ghumra11-Oct-13 21:11 
GeneralRe: My vote of 1 Pin
Rodrigo Ratan [R2]6-Nov-13 9:43
Rodrigo Ratan [R2]6-Nov-13 9:43 

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

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