Zip or UnZip Files in .NET

Overview

This article will teach you how to programmatically compress Zip files using a variety of methods utilising C# or the.NET API and sample code. You will learn how to zip or compress one or more files, as well as how to zip files simultaneously. You will also learn how to decompress or unzip files as well.

Zip or Compress files in C# and Decompress or Unzip files in C#

Aspose.ZIP API lets you compress and decompress files without worrying about the underlying file structure. This article shows working with single as well as multiple file compression.

Compressing Files

Compressing Single File

Steps: Compressing Single File in C#

  1. Create a file stream with the desired name of your output zip file.
  2. Create file stream of the data file to be compressed.
  3. Create an instance of Archive class and pass it instance of ArchiveEntrySettings class.
  4. Add data file created in step 2 using Archive.CreateEntry method.
  5. Zip the data file using Archive.Save method and pass it the file stream created in step 1.
 1// For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
 2using (FileStream zipFile = File.Open(dataDir + "CompressSingleFile_out.zip", FileMode.Create))
 3{
 4    //File to be added to archive
 5    using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
 6    {
 7        using (var archive = new Archive(new ArchiveEntrySettings()))
 8        {
 9            archive.CreateEntry("alice29.txt", source1);
10            
11            archive.Save(zipFile);
12        }
13    }
14}

Compressing Multiple Files

Steps: Compressing Multiple Files in C#

  1. Create a file stream with the desired name of your output zip file.
  2. Create file stream of the first data file to be compressed.
  3. Create file stream of the second data file to be compressed.
  4. Create an instance of Archive class.
  5. Add data files created in step 2 and step 3 using Archive.CreateEntry method.
  6. Create an instance of ArchiveSaveOptions class.
  7. Zip the data files using Archive.Save method and pass it the file stream created in step 1 and instance of ArchiveSaveOptions created in above step.
 1// For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
 2using (FileStream zipFile = File.Open(dataDir + "CompressMultipleFiles_out.zip", FileMode.Create))
 3{
 4    using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
 5    {
 6        using (FileStream source2 = File.Open(dataDir + "asyoulik.txt", FileMode.Open, FileAccess.Read))
 7        {
 8            using (var archive = new Archive())
 9            {
10                archive.CreateEntry("alice29.txt", source1);
11                archive.CreateEntry("asyoulik.txt", source2);
12                archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII, ArchiveComment = "There are two poems from Canterbury corpus" });
13            }
14        }
15    }
16}

Compress Files by File Info

Steps: Compress Files by File Info in C#

  1. Open a file stream with FileMode.Create with the desired name of your output zip file.
  2. Create FileInfo object of your first data file to be compressed.
  3. Create FileInfo object of your second data file to be compressed.
  4. Create an instance of Archive class.
  5. Add data files created in step 2 and step 3 using Archive.CreateEntry method.
  6. Create an instance of ArchiveSaveOptions class.
  7. Zip the data files using Archive.Save method and pass it the file stream created in step 1 and instance of ArchiveSaveOptions created in above step.
 1// For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
 2using (FileStream zipFile = File.Open(dataDir + "CompressFilesByFileInfo_out.zip", FileMode.Create))
 3{
 4    FileInfo fi1 = new FileInfo(dataDir + "alice29.txt");
 5    FileInfo fi2 = new FileInfo(dataDir + "fields.c");
 6
 7    using (var archive = new Archive())
 8    {
 9        archive.CreateEntry("alice29.txt", fi1);
10        archive.CreateEntry("fields.c", fi2);
11        archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII });
12    }
13}

Storing Files to Archives without Compression

Steps: Storing Files to Archives without Compression using C#

  1. Open a file stream with FileMode.Create with the desired name of your output zip file.
  2. Create FileInfo objects for your data files to be stored in archive.
  3. Create an instance of ArchiveEntrySettings class and pass it instance of StoreCompressionSettings class.
  4. Create an instance of Archive class and pass it instance of ArchiveEntrySettings class created in above step.
  5. Add FileInfo objects created in step 2 using Archive.CreateEntry method.
  6. Create instance of ArchiveSaveOptions and set Encoding = Encoding.ASCII.
  7. Zip the data files using Archive.Save method and pass it the file stream created in step 1 and instance of ArchiveSaveOptions created in above step.
 1// For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
 2//Creates zip archive without compressing files
 3using (FileStream zipFile = File.Open(dataDir + "StoreMultipleFilesWithoutCompression_out.zip", FileMode.Create))
 4{
 5    FileInfo fi1 = new FileInfo(dataDir + "alice29.txt");
 6    FileInfo fi2 = new FileInfo(dataDir + "lcet10.txt");
 7
 8    using (Archive archive = new Archive(new ArchiveEntrySettings(new StoreCompressionSettings())))
 9    {
10        archive.CreateEntry("alice29.txt", fi1);
11        archive.CreateEntry("lcet10.txt", fi2);
12        archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII });
13    }
14
15}

Using Parallelism to Compress Files

Steps: Using Parallelism to Compress Files using C#

  1. Open a file stream with FileMode.Create with the desired name of your output zip file.
  2. Open file streams with FileMode.Open and FileAccess.Read for your first and second data files to be compressed.
  3. Create an instance of Archive class.
  4. Add data files created in step 2 using Archive.CreateEntry method.
  5. Create an instance of ParallelOptions and set ParallelCompressInMemory = ParallelCompressionMode.Always.
  6. Create an instance of ArchiveSaveOptions and set its property ParallelOptions with the above instance.
  7. Zip the data files using Archive.Save method and pass it the file stream created in step 1 and instance of ArchiveSaveOptions created in above step.
 1// For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
 2using (FileStream zipFile = File.Open(dataDir + "UsingParallelismToCompressFiles_out.zip", FileMode.Create))
 3{
 4    using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
 5    {
 6        using (FileStream source2 = File.Open(dataDir + "asyoulik.txt", FileMode.Open, FileAccess.Read))
 7        {
 8            using (var archive = new Archive())
 9            {
10                archive.CreateEntry("alice29.txt", source1);
11                archive.CreateEntry("asyoulik.txt", source2);
12                //Define the parallelism criterion
13                var parallelOptions = new ParallelOptions
14                {
15                    ParallelCompressInMemory = ParallelCompressionMode.Always
16                };
17                archive.Save(zipFile,
18                    new ArchiveSaveOptions()
19                    {
20                        ParallelOptions = parallelOptions,
21                        Encoding = Encoding.ASCII,
22                        ArchiveComment = "There are two poems from Canterbury corpus"
23                    });
24            }
25        }
26    }
27}

LZMA Compression within ZIP Archive

The Lempel–Ziv–Markov chain algorithm (LZMA) is an algorithm used to perform lossless data compression. LZMA uses a dictionary compression algorithm, the compressed stream is a stream of bits. LZMA compression within the ZIP archive allows ZIP containers to contain LZMA compressed entries. The following code example shows the implementation of LZMA compression using Aspose.ZIP API.

Steps: LZMA Compression within ZIP Archive using C#

  1. Open a file stream with FileMode.Create with the desired name of your output zip file.
  2. Create an instance of ArchiveEntrySettings and pass it the instance of LzmaCompressionSettings class.
  3. Create an instance of Archive class and pass it the instance of ArchiveEntrySettings created above.
  4. Add data files to be compressed via file paths using Archive.CreateEntry method.
  5. Zip the data files using Archive.Save method.
1using (FileStream zipFile = File.Open(dataDir + "LZMACompression_out.zip", FileMode.Create))
2{
3    using (Archive archive = new Archive(new ArchiveEntrySettings(new LzmaCompressionSettings())))
4    {
5        archive.CreateEntry("sample.txt", dataDir + "sample.txt");
6        archive.Save(zipFile);
7    }
8}

BZip2 Compression within ZIP Archive

BZip2 compression settings allow ZIP container to contain BZip2 compressed entries. The following code example shows the implementation of BZip2 compression using Aspose.ZIP API.

Steps: BZip2 Compression within ZIP Archive using C#

  1. Open a file stream with FileMode.Create with the desired name of your output zip file.
  2. Create an instance of ArchiveEntrySettings and pass it the instance of Bzip2CompressionSettings class.
  3. Create an instance of Archive class and pass it the instance of ArchiveEntrySettings created above.
  4. Add data files to be compressed via file paths using Archive.CreateEntry method.
  5. Zip the data files using Archive.Save method.
1using (FileStream zipFile = File.Open(dataDir + "Bzip2Compression_out.zip", FileMode.Create))
2{
3    using (Archive archive = new Archive(new ArchiveEntrySettings(new Bzip2CompressionSettings())))
4    {
5        archive.CreateEntry("sample.txt", dataDir + "sample.txt");
6        archive.Save(zipFile);
7    }
8}

PPMd Compression within ZIP Archive

PPMd compression settings allow ZIP container to contain PPMd compressed entries. The following code example demonstrated the implementation of PPMd compression using Aspose.ZIP API.

Steps: PPMd Compression within ZIP Archive using C#

  1. Open a file stream with FileMode.Create with the desired name of your output zip file.
  2. Create an instance of ArchiveEntrySettings and pass it the instance of PPMdCompressionSettings class.
  3. Create an instance of Archive class and pass it the instance of ArchiveEntrySettings created above.
  4. Add data files to be compressed via file paths using Archive.CreateEntry method.
  5. Zip the data files using Archive.Save method.
1using (FileStream zipFile = File.Open(dataDir + "PPMdCompression_out.zip", FileMode.Create))
2{
3    using (Archive archive = new Archive(new ArchiveEntrySettings(new PPMdCompressionSettings())))
4    {
5        archive.CreateEntry("sample.txt", dataDir + "sample.txt");
6        archive.Save(zipFile);
7    }
8}

Decompressing Archives

Decompress Archive having Single File

 1// For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
 2using (FileStream fs = File.OpenRead(dataDir + "CompressSingleFile_out.zip"))
 3{
 4    using (Archive archive = new Archive(fs))
 5    {
 6        int percentReady = 0;
 7        archive.Entries[0].ExtractionProgressed += (s, e) =>
 8        {
 9            int percent = (int)((100 * e.ProceededBytes) / ((ArchiveEntry)s).UncompressedSize);
10            if (percent > percentReady)
11            {
12                Console.WriteLine(string.Format("{0}% decompressed", percent));
13                percentReady = percent;
14            }
15        };
16        archive.Entries[0].Extract(dataDir + "alice_extracted_out.txt");
17    }
18}

Decompress Archive having Multiple Files

 1// For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
 2using (FileStream zipFile = File.Open(dataDir + "CompressMultipleFiles_out.zip", FileMode.Open))
 3{
 4    StringBuilder sb = new StringBuilder("Entries are: ");
 5    int percentReady = 0;
 6    using (Archive archive = new Archive(zipFile,
 7        new ArchiveLoadOptions()
 8        {
 9            EntryListed = (s, e) => { sb.AppendFormat("{0}, ", e.Entry.Name); },
10            EntryExtractionProgressed = (s, e) =>
11            {
12                int percent = (int)((100 * e.ProceededBytes) / ((ArchiveEntry)s).UncompressedSize);
13                if (percent > percentReady)
14                {
15                    Console.WriteLine(string.Format("{0}% compressed", percent)); percentReady = percent;
16                }
17            }
18        }))
19    {
20        Console.WriteLine(sb.ToString(0, sb.Length - 2));
21        using (var extracted = File.Create(dataDir + "alice_extracted_out.txt"))
22        {
23            using (var decompressed = archive.Entries[0].Open())
24            {
25                byte[] buffer = new byte[8192];
26                int bytesRead;
27                while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
28                {
29                    extracted.Write(buffer, 0, bytesRead);
30                }
31                // Read from decompressed stream to extracting file.
32            }
33        }
34        percentReady = 0;
35        archive.Entries[1].Extract(dataDir + "asyoulik_extracted_out.txt");
36    }
37}

Extract Stored Archive without Compression

 1// For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
 2using (FileStream zipFile = File.Open(dataDir + "StoreMultipleFilesWithoutCompression_out.zip", FileMode.Open))
 3{
 4    using (Archive archive = new Archive(zipFile))
 5    {
 6        using (var extracted = File.Create(dataDir + "alice_extracted_store_out.txt"))
 7        {
 8            using (var decompressed = archive.Entries[0].Open())
 9            {
10                byte[] buffer = new byte[8192];
11                int bytesRead;
12                while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
13                {
14                    extracted.Write(buffer, 0, bytesRead);
15                }
16                // Read from decompressed stream to extracting file.
17            }
18        }
19
20        using (var extracted = File.Create(dataDir + "asyoulik_extracted_store_out.txt"))
21        {
22            using (var decompressed = archive.Entries[1].Open())
23            {
24                byte[] buffer = new byte[8192];
25                int bytesRead;
26                while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
27                {
28                    extracted.Write(buffer, 0, bytesRead);
29                }
30                // Read from decompressed stream to extracting file.
31            }
32        }
33    }
34}
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.