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#
- Create a file stream with the desired name of your output zip file.
- Create file stream of the data file to be compressed.
- Create an instance of Archive class and pass it instance of ArchiveEntrySettings class.
- Add data file created in step 2 using Archive.CreateEntry method.
- 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
2 using (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#
- Create a file stream with the desired name of your output zip file.
- Create file stream of the first data file to be compressed.
- Create file stream of the second data file to be compressed.
- Create an instance of Archive class.
- Add data files created in step 2 and step 3 using Archive.CreateEntry method.
- Create an instance of ArchiveSaveOptions class.
- 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 using (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 }
17
Compress Files by File Info
Steps: Compress Files by File Info in C#
- Open a file stream with FileMode.Create with the desired name of your output zip file.
- Create FileInfo object of your first data file to be compressed.
- Create FileInfo object of your second data file to be compressed.
- Create an instance of Archive class.
- Add data files created in step 2 and step 3 using Archive.CreateEntry method.
- Create an instance of ArchiveSaveOptions class.
- 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 using (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 }
14
Storing Files to Archives without Compression
Steps: Storing Files to Archives without Compression using C#
- Open a file stream with FileMode.Create with the desired name of your output zip file.
- Create FileInfo objects for your data files to be stored in archive.
- Create an instance of ArchiveEntrySettings class and pass it instance of StoreCompressionSettings class.
- Create an instance of Archive class and pass it instance of ArchiveEntrySettings class created in above step.
- Add FileInfo objects created in step 2 using Archive.CreateEntry method.
- Create instance of ArchiveSaveOptions and set Encoding = Encoding.ASCII.
- 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
3 using (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 }
16
Using Parallelism to Compress Files
Steps: Using Parallelism to Compress Files using C#
- Open a file stream with FileMode.Create with the desired name of your output zip file.
- Open file streams with FileMode.Open and FileAccess.Read for your first and second data files to be compressed.
- Create an instance of Archive class.
- Add data files created in step 2 using Archive.CreateEntry method.
- Create an instance of ParallelOptions and set ParallelCompressInMemory = ParallelCompressionMode.Always.
- Create an instance of ArchiveSaveOptions and set its property ParallelOptions with the above instance.
- 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 using (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 }
28
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#
- Open a file stream with FileMode.Create with the desired name of your output zip file.
- Create an instance of ArchiveEntrySettings and pass it the instance of LzmaCompressionSettings class.
- Create an instance of Archive class and pass it the instance of ArchiveEntrySettings created above.
- Add data files to be compressed via file paths using Archive.CreateEntry method.
- Zip the data files using Archive.Save method.
1 using (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#
- Open a file stream with FileMode.Create with the desired name of your output zip file.
- Create an instance of ArchiveEntrySettings and pass it the instance of Bzip2CompressionSettings class.
- Create an instance of Archive class and pass it the instance of ArchiveEntrySettings created above.
- Add data files to be compressed via file paths using Archive.CreateEntry method.
- Zip the data files using Archive.Save method.
1 using (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 }
9
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#
- Open a file stream with FileMode.Create with the desired name of your output zip file.
- Create an instance of ArchiveEntrySettings and pass it the instance of PPMdCompressionSettings class.
- Create an instance of Archive class and pass it the instance of ArchiveEntrySettings created above.
- Add data files to be compressed via file paths using Archive.CreateEntry method.
- Zip the data files using Archive.Save method.
1 using (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 }
9
Decompressing Archives
Decompress Archive having Single File
Steps: Decompress a Single File from an Archive using C#
- Open a file stream for the input ZIP file using FileMode.OpenRead.
- Create an instance of the Archive class by passing the file stream to the constructor.
- Monitor the decompression progress using the ExtractionProgressed event of the archive entry.
- Extract the single file from the archive using the Extract method, specifying the output file path.
- Display the decompression progress as a percentage in the console
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (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 }
19
Decompress Archive having Multiple Files
Steps: Decompress Multiple Files from an Archive using C#
- Open a file stream for the input ZIP file using FileMode.Open.
- Create an instance of the Archive class with custom load options to list entries and track decompression progress.
- Display the names of all the archive entries using the EntryListed event.
- Monitor decompression progress with the EntryExtractionProgressed event, displaying progress in the console.
- Extract multiple files from the archive, using the Extract method and reading data into the output files.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (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 }
38
Extract Stored Archive without Compression
Steps: Extract Files from an Archive and Save to Disk using C#
- Open the ZIP file and create an instance of the Archive class.
- Extract the first file from the archive by opening the entry’s stream and writing its content to a new file.
- Use a buffer to read data from the decompressed stream and save it to the output file.
- Repeat the process for the second file in the archive, writing its content to a separate output file.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (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 }
35