KNOWLEDGEBASE
Zip or unzip files using C# - Files compression and decompression
What is ZIP (File format)
ZIP is an archive file format that supports lossless data compression. A ZIP file may contain one or more files or directories that may have been compressed. ZIP files generally use the file extensions .zip or .ZIP and the MIME media type application/zip. ZIP is used as a base file format by many programs, usually under a different name. When navigating a file system via a user interface, graphical icons representing ZIP files often appear as a document or other object prominently featuring a zipper. There are multiple ways to zip (compress) files, depends which operating system you use. And almost every day, we are supposed to zip or unzip some files and forward them to some storage server or file-sharing platform. Fortunately, we can automate that process using Aspose.ZIP API. It 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. Aspose.ZIP package can be added to your .NET project using the following NuGet command:
PM> Install-Package Aspose.Zip
How to compress a single file with C#
- First we need to create a object of FileStream class for the output ZIP archive
- Load a single file into the FileStream object
- Create an object of the Archive class
- Add the file into the archive using Archive.CreateEntry( “FileName”, FileStream) method.
- Create the ZIP archive using Archive.Save(FileStream) method.
using (FileStream zipFile = File.Open(dataDir + "CompressSingleFile_out.zip", FileMode.Create))
{
//File to be added to archive
using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
{
using (var archive = new Archive(new ArchiveEntrySettings()))
{
archive.CreateEntry("alice29.txt", source1);
archive.Save(zipFile);
}
}
}
Compressing multiple files with C#
The difference between compressing a single file and multiple files is that we have to load more files into the FileStream and add them all to the ZIP archive using the method Archive.CreateEntry(“FileName”, FileStream) The following code snippet shows how to add multiple files into the ZIP using FileStream.
// Create FileStream for output ZIP archive
using (FileStream zipFile = File.Open("compressed_files.zip", FileMode.Create))
{
// File to be added to archive
using (FileStream source1 = File.Open("alice29.txt", FileMode.Open, FileAccess.Read))
{
// File to be added to archive
using (FileStream source2 = File.Open("asyoulike.txt", FileMode.Open, FileAccess.Read))
{
using (var archive = new Archive())
{
// Add files to the archive
archive.CreateEntry("alice29.txt", source1);
archive.CreateEntry("asyoulik3.txt", source2);
// ZIP the files
archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII, ArchiveComment = "two files are compressed in this archive" });
}
}
}
}
Compress files using FileInfo Class
Files can also be loaded using the FileInfo class and later added to the ZIP archive the same way as before. FileInfo class provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
using (FileStream zipFile = File.Open("compressed_files.zip", FileMode.Create))
{
// Files to be added to archive
FileInfo fi1 = new FileInfo("alice29.txt");
FileInfo fi2 = new FileInfo("fields.c");
using (var archive = new Archive())
{
// Add files to the archive
archive.CreateEntry("alice29.txt", fi1);
archive.CreateEntry("fields.c", fi2);
// Create ZIP archive
archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII });
}
}
Storing Files to Archives without Compression
//Creates zip archive without compressing files
using (FileStream zipFile = File.Open(dataDir + "StoreMultipleFilesWithoutCompression_out.zip", FileMode.Create))
{
FileInfo fi1 = new FileInfo(dataDir + "alice29.txt");
FileInfo fi2 = new FileInfo(dataDir + "lcet10.txt");
using (Archive archive = new Archive(new ArchiveEntrySettings(new StoreCompressionSettings())))
{
archive.CreateEntry("alice29.txt", fi1);
archive.CreateEntry("lcet10.txt", fi2);
archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII });
}
}
How to ZIP files with password in C#
using (var archive = new Archive(new ArchiveEntrySettings(encryptionSettings: new TraditionalEncryptionSettings("pass"))))
{
archive.CreateEntry("entry_name1.dat", "input_file1.dat");
archive.CreateEntry("entry_name2.dat", "input_file2.dat");
archive.Save("result_archive.zip");
}
The encryptionSettings parameter is used to create a password-protected ZIP archive.
How to UnZIP files with password in C#
using (var archive = new Archive("input_archive.zip", new ArchiveLoadOptions{DecryptionPassword = "pass"}))
{
archive.ExtractToDirectory("\\outputDirectory");
}
The ArchiveLoadOptions with DecryptionPassword property value is used to open a password-protected ZIP archive. To see complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET.
Using 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.
using (FileStream zipFile = File.Open(dataDir + "LZMACompression_out.zip", FileMode.Create))
{
using (Archive archive = new Archive(new ArchiveEntrySettings(new LzmaCompressionSettings())))
{
archive.CreateEntry("sample.txt", dataDir + "sample.txt");
archive.Save(zipFile);
}
}
Using BZip2 Compression within ZIP Archive
bzip2 is a free and open-source file compression program that uses the Burrows–Wheeler algorithm. It only compresses single files and is not a file archiver. It was developed by Julian Seward, and maintained by Mark Wielaard and Micah Snyder. The following code snippet shows the implementation of BZip2 compression using Aspose.ZIP API.
using (FileStream zipFile = File.Open(dataDir + "Bzip2Compression_out.zip", FileMode.Create))
{
using (Archive archive = new Archive(new ArchiveEntrySettings(new Bzip2CompressionSettings())))
{
archive.CreateEntry("sample.txt", dataDir + "sample.txt");
archive.Save(zipFile);
}
}
Using PPMd Compression within ZIP Archive
Prediction by partial matching (PPM) is an adaptive statistical data compression technique based on context modeling and prediction. PPM models use a set of previous symbols in the uncompressed symbol stream to predict the next symbol in the stream. PPM algorithms can also be used to cluster data into predicted groupings in cluster analysis. The following code snippet shows the implementation of PPMd compression using Aspose.ZIP API.
using (FileStream zipFile = File.Open(dataDir + "PPMdCompression_out.zip", FileMode.Create))
{
using (Archive archive = new Archive(new ArchiveEntrySettings(new PPMdCompressionSettings())))
{
archive.CreateEntry("sample.txt", dataDir + "sample.txt");
archive.Save(zipFile);
}
}
Decompress Archive with Single File
using (FileStream fs = File.OpenRead(dataDir + "CompressSingleFile_out.zip"))
{
using (Archive archive = new Archive(fs))
{
int percentReady = 0;
archive.Entries[0].ExtractionProgressed += (s, e) =>
{
int percent = (int)((100 * e.ProceededBytes) / ((ArchiveEntry)s).UncompressedSize);
if (percent > percentReady)
{
Console.WriteLine(string.Format("{0}% decompressed", percent));
percentReady = percent;
}
};
archive.Entries[0].Extract(dataDir + "alice_extracted_out.txt");
}
}
Decompress Archive with Multiple Files
using (FileStream zipFile = File.Open(dataDir + "CompressMultipleFiles_out.zip", FileMode.Open))
{
StringBuilder sb = new StringBuilder("Entries are: ");
int percentReady = 0;
using (Archive archive = new Archive(zipFile,
new ArchiveLoadOptions()
{
EntryListed = (s, e) => { sb.AppendFormat("{0}, ", e.Entry.Name); },
EntryExtractionProgressed = (s, e) =>
{
int percent = (int)((100 * e.ProceededBytes) / ((ArchiveEntry)s).UncompressedSize);
if (percent > percentReady)
{
Console.WriteLine(string.Format("{0}% compressed", percent)); percentReady = percent;
}
}
}))
{
Console.WriteLine(sb.ToString(0, sb.Length - 2));
using (var extracted = File.Create(dataDir + "alice_extracted_out.txt"))
{
using (var decompressed = archive.Entries[0].Open())
{
byte[] buffer = new byte[8192];
int bytesRead;
while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
{
extracted.Write(buffer, 0, bytesRead);
}
// Read from decompressed stream to extracting file.
}
}
percentReady = 0;
archive.Entries[1].Extract(dataDir + "asyoulik_extracted_out.txt");
}
}
Extract Stored Archive without Compression
using (FileStream zipFile = File.Open(dataDir + "StoreMultipleFilesWithoutCompression_out.zip", FileMode.Open))
{
using (Archive archive = new Archive(zipFile))
{
using (var extracted = File.Create(dataDir + "alice_extracted_store_out.txt"))
{
using (var decompressed = archive.Entries[0].Open())
{
byte[] buffer = new byte[8192];
int bytesRead;
while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
{
extracted.Write(buffer, 0, bytesRead);
}
// Read from decompressed stream to extracting file.
}
}
using (var extracted = File.Create(dataDir + "asyoulik_extracted_store_out.txt"))
{
using (var decompressed = archive.Entries[1].Open())
{
byte[] buffer = new byte[8192];
int bytesRead;
while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
{
extracted.Write(buffer, 0, bytesRead);
}
// Read from decompressed stream to extracting file.
}
}
}
}
For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET