
In the previous post, I discussed several ways to create ZIP archives with C#, including encrypted and password‑protected files. Besides ZIP, other popular formats are 7z, tar, and RAR. The 7z format uses an open‑source architecture, offers a high compression ratio, supports 256‑bit AES encryption, and can encrypt file names. This article shows how to create 7z (7‑Zip) archives programmatically using C#.
This article is divided into the following sections:
- Create a 7z (7‑Zip) Archive using C#
- Create an AES Encrypted 7z Archive using C#
- Set Different Passwords for 7z Entries using C#
All steps and code samples rely on Aspose.ZIP for .NET. Install the API using one of these methods:
- Install via NuGet Package Manager.
- Download the DLL and add a reference to your project.
Create 7z (7‑Zip) Archive using C#
You may need to compress a single file or many files into a 7z archive. Both scenarios are covered below.
Create 7z Archive with Single Entry
Steps to create a 7z archive that contains one file:
- Open a new FileStream for the 7z file.
- Instantiate a SevenZipArchive object.
- Add the file with SevenZipArchive.CreateEntry(String, String, Boolean, SevenZipEntrySettings).
- Save the archive using SevenZipArchive.Save(Stream).
The code sample demonstrates how to create a 7z (7‑Zip) archive in C#.
Create 7z Archive with Multiple Entries
To add several files, place them in a folder and pass the folder path to SevenZipArchive.CreateEntries(). Follow these steps:
- Create a SevenZipArchive instance.
- Call SevenZipArchive.CreateEntries(String, Boolean) with the folder path.
- Save the archive using SevenZipArchive.Save(String).
The code sample shows how to create a 7z archive with multiple entries in C#.
Create an AES Encrypted 7z Archive using C#
The 7z format supports AES encryption for added security. Use the SevenZipAESEncryptionSettings class to encrypt a 7z file. The sample below creates an AES‑encrypted 7z archive in C#.
Set Different Passwords for 7z Entries using C#
You can assign a unique password to each file entry in a 7z archive. To do this:
- Open a new FileStream for the archive.
- Access each file with the FileInfo class.
- Create a SevenZipArchive instance.
- Add entries using SevenZipArchive.CreateEntry(String, FileInfo, Boolean, SevenZipEntrySettings).
- Save the archive with SevenZipArchive.Save(Stream).
The following code sample sets a password for every entry in a 7z archive.
Conclusion
We have shown how to create 7z archives programmatically in C#, how to apply AES encryption, and how to set individual passwords for each entry. Learn more about compression and decompression here.