Working with 7z Archives
Overview
7-Zip is a file archiver with a high compression ratio. Aspose.ZIP for .NET provides the SevenZipArchive class for composing, updating, and extracting 7z archives, and the SevenZipArchiveEntry class for working with individual entries.
With Aspose.ZIP you can:
- Create 7z archives from file paths,
FileInfo, streams, stream providers, or whole directories. - Use LZMA, LZMA2, BZip2, PPMd, or Store compression methods.
- Tune codec parameters such as dictionary size, fast bytes, and literal context bits.
- Compose solid archives and compress archive headers.
- Preserve file metadata when entries are created from
FileInfo. - Encrypt entries with AES, optionally encrypting the header as well.
- Append entries to existing 7z archives and save the result to a new file, the same file, or split volumes.
- Extract whole archives or individual entries, including archives that use Delta and BCJ filter chains.
- Track compression progress and cancel extraction with
CancellationToken.
The AES-256 method is the encryption method used for 7z archives. Header encryption is also supported, but it cannot be combined with per-entry passwords or with CompressHeader = true.
Create a 7-Zip Archive
The following code example demonstrates how to create a simple 7z archive with one entry.
1 using (FileStream sevenZipFile = File.Open("archive.7z", FileMode.Create))
2 {
3 using (SevenZipArchive archive = new SevenZipArchive())
4 {
5 archive.CreateEntry("data.bin", "file.dat");
6 archive.Save(sevenZipFile);
7 }
8 }Create Entries from a Directory
The CreateEntries methods recursively add files from a directory.
1 using (SevenZipArchive archive = new SevenZipArchive())
2 {
3 archive.CreateEntries(@"C:\Data\Corpus");
4 archive.Save("SevenZip.7z");
5 }Use FileInfo and Preserve Metadata
If you create entries from FileInfo, Aspose.ZIP keeps file timestamps in the archive.
1 FileInfo fi1 = new FileInfo("alice29.txt");
2 FileInfo fi2 = new FileInfo("asyoulik.txt");
3
4 using (SevenZipArchive archive = new SevenZipArchive())
5 {
6 archive.CreateEntry("alice29.txt", fi1);
7 archive.CreateEntry("asyoulik.txt", fi2);
8 archive.Save("archive.7z");
9 }Use Different Compression Methods
Aspose.ZIP supports LZMA, LZMA2, BZip2, PPMd, and Store compression for 7z composition. The next sample shows LZMA2 with custom parameters:
1 using (FileStream sevenZipFile = File.Open("archive.7z", FileMode.Create))
2 {
3 SevenZipEntrySettings settings = new SevenZipEntrySettings(new SevenZipLZMA2CompressionSettings(1 << 24, 64));
4
5 using (SevenZipArchive archive = new SevenZipArchive(settings))
6 {
7 archive.CreateEntry("alice29.txt", "alice29.txt");
8 archive.Save(sevenZipFile);
9 }
10 }For LZMA, you can also tune settings such as DictionarySize, FastBytes, and LiteralContextBits. The test suite covers these combinations as well.
Solid Archives and Compressed Headers
Solid archives are useful when entries share redundant data. You can also compress the archive header.
1 using (SevenZipArchive archive = new SevenZipArchive(new SevenZipEntrySettings(new SevenZipLZMA2CompressionSettings())
2 {
3 Solid = true,
4 CompressHeader = true
5 }))
6 {
7 archive.CreateEntries(@"C:\Data\Corpus");
8 archive.Save("Solid.7z");
9 }Create Entries from a Stream Provider
Use a stream provider when the source stream should be opened only when the archive is being saved.
1 using (FileStream sevenZipFile = File.Open("archive.7z", FileMode.Create))
2 {
3 using (SevenZipArchive archive = new SevenZipArchive())
4 {
5 archive.CreateEntry("alice29.txt", () => File.OpenRead("alice29.txt"));
6 archive.Save(sevenZipFile);
7 }
8 }Report Compression Progress
Every SevenZipArchiveEntry exposes the CompressionProgressed event.
1 using (FileStream sevenZipFile = File.Open("archive.7z", FileMode.Create))
2 using (FileStream source = File.Open("kennedy.xls", FileMode.Open, FileAccess.Read))
3 using (SevenZipArchive archive = new SevenZipArchive(new SevenZipEntrySettings(new SevenZipLZMA2CompressionSettings())))
4 {
5 SevenZipArchiveEntry entry = archive.CreateEntry("kennedy.xls", source);
6 int percentReady = 0;
7
8 entry.CompressionProgressed += (s, e) =>
9 {
10 int percent = (int)((100 * (long)e.ProceededBytes) / source.Length);
11 if (percent > percentReady)
12 percentReady = percent;
13 };
14
15 archive.Save(sevenZipFile);
16 }Encrypt 7-Zip Archives
The following code example demonstrates how to create an encrypted 7z archive with AES and encrypted headers.
1 using (SevenZipArchive archive = new SevenZipArchive(
2 new SevenZipEntrySettings(
3 new SevenZipLZMA2CompressionSettings(),
4 new SevenZipAESEncryptionSettings("p@s$") { EncryptHeader = true })))
5 {
6 archive.CreateEntry("alice29.txt", "alice29.txt");
7 archive.CreateEntry("asyoulik.txt", "asyoulik.txt");
8 archive.Save("encrypted.7z");
9 }You can also encrypt only selected entries, or use different passwords for different entries, as long as header encryption is not enabled.
Set Different Passwords for Entries
The following code example demonstrates how to create an archive with a different password for each encrypted entry.
1 using (FileStream sevenZipFile = File.Open("archive.7z", FileMode.Create))
2 {
3 FileInfo fi1 = new FileInfo("data1.bin");
4 FileInfo fi2 = new FileInfo("data2.bin");
5 FileInfo fi3 = new FileInfo("data3.bin");
6 using (var archive = new SevenZipArchive())
7 {
8 archive.CreateEntry("entry1.bin", fi1, false, new SevenZipEntrySettings(new SevenZipStoreCompressionSettings(), new SevenZipAESEncryptionSettings("test1")));
9 archive.CreateEntry("entry2.bin", fi2, false, new SevenZipEntrySettings(new SevenZipStoreCompressionSettings(), new SevenZipAESEncryptionSettings("test2")));
10 archive.CreateEntry("entry3.bin", fi3, false, new SevenZipEntrySettings(new SevenZipStoreCompressionSettings(), new SevenZipAESEncryptionSettings("test3")));
11 archive.Save(sevenZipFile);
12 }
13 }The API also supports custom AES key-derivation parameters, so password-based encryption is not limited to the default settings.
Append or Resave Existing 7-Zip Archives
Aspose.ZIP can open an existing 7z archive, append new entries, and then save the result either to another file or in place.
1 using (SevenZipArchive archive = new SevenZipArchive("base.7z"))
2 {
3 archive.CreateEntry(
4 "sum",
5 new MemoryStream(File.ReadAllBytes("sum")),
6 new SevenZipEntrySettings(new SevenZipLZMA2CompressionSettings()));
7
8 archive.Save("result.7z");
9 }This also works for archives with compressed headers and encrypted headers. If the archive has an encrypted header, open it with the password first:
1 using (SevenZipArchive archive = new SevenZipArchive("encrypted.7z", "p@s$"))
2 {
3 archive.CreateEntry("appended.bin", new MemoryStream(new byte[] { 1, 2, 3 }));
4 archive.Save("result.7z");
5 }Save Appended Archives as Split Volumes
After appending entries, you can write the resulting archive as split 7z volumes:
1 byte[] second = File.ReadAllBytes("second.bin");
2
3 using (SevenZipArchive archive = new SevenZipArchive("base.7z"))
4 {
5 archive.CreateEntry("second.bin", new MemoryStream(second));
6 archive.SaveSplit(@"C:\out", new SplitSevenZipArchiveSaveOptions("result_append_split", 65536));
7 }Extract 7-Zip Archives
The test suite covers extraction of LZMA, LZMA2, BZip2, PPMd, Store, Delta, and BCJ-filtered 7z archives, including solid archives and archives containing empty files.
The following code example demonstrates how to extract 7z archive to directory.
1 using (SevenZipArchive archive = new SevenZipArchive("archive.7z"))
2 {
3 archive.ExtractToDirectory("ExtractionFolder");
4 }Extract Individual Entries
If you only need a specific entry, open or extract that entry directly:
1 using (SevenZipArchive archive = new SevenZipArchive("archive.7z"))
2 {
3 using (MemoryStream ms = new MemoryStream())
4 {
5 archive.Entries[0].Extract(ms);
6 }
7 }Cancel Extraction
Use
SevenZipLoadOptions with a CancellationToken when extraction may need to be interrupted.
1 using (CancellationTokenSource cts = new CancellationTokenSource())
2 {
3 SevenZipLoadOptions options = new SevenZipLoadOptions() { CancellationToken = cts.Token };
4 cts.CancelAfter(20);
5
6 using (SevenZipArchive archive = new SevenZipArchive("archive.7z", options))
7 {
8 archive.ExtractToDirectory("ExtractionFolder");
9 }
10 }