Create ZIP in C#

Introduction to ZIP Archives

ZIP archives are crucial for compressing and consolidating multiple files or folders into a single container. This format not only minimizes file size for storage and transmission but also preserves metadata, simplifying file management. ZIP archives are widely utilized in both desktop and web applications for tasks like uploading, downloading, sharing, and securing files through encryption.

In this article, we will delve into various methods for programmatically creating ZIP archives in C#. By the end, you’ll know how to:

C# ZIP Library

The Aspose.ZIP for .NET is a powerful API tailored for zipping and unzipping files and folders within .NET applications. It features AES encryption to secure your files within ZIP archives. You can easily install the API from NuGet or download the binaries from the Downloads section.

Create a ZIP Archive in C#

To compress a file into a ZIP archive, follow these steps:

  1. Create a FileStream object for the output ZIP archive.
  2. Open the source file with a FileStream object.
  3. Instantiate the Archive class.
  4. Add the file to the archive using the Archive.CreateEntry(string, FileStream) method.
  5. Save the ZIP archive with the Archive.Save(FileStream) method.

Here’s a code sample demonstrating how to add a file to a ZIP archive using C#:

using Aspose.Zip;
using Aspose.Zip.Saving;
// Create FileStream for output ZIP archive
using (FileStream zipFile = File.Open("compress_directory.zip", FileMode.Create))
{
	using (Archive archive = new Archive(new ArchiveEntrySettings(null, new AesEcryptionSettings("p@s$", EncryptionMethod.AES128))))
	{
		// Add folder to archive
		DirectoryInfo corpus = new DirectoryInfo("CanterburyCorpus");
		archive.CreateEntries(corpus);
		// Create ZIP archive
		archive.Save(zipFile);
	}
}

Add Multiple Files to a ZIP Archive in C#

To add multiple files to a ZIP archive, you can choose from the following methods:

Using FileStream

Utilize the FileStream class to zip files in C# by adding multiple files to the ZIP archive with the Archive.CreateEntry(String, FileStream) method. Here’s how:

using Aspose.Zip;
using Aspose.Zip.Saving;
// Create FileStream for output ZIP archive
using (FileStream zipFile = File.Open("compress_directory.zip", FileMode.Create))
{
	using (Archive archive = new Archive(new ArchiveEntrySettings(null, new AesEcryptionSettings("p@s$", EncryptionMethod.AES128))))
	{
		// Add folder to archive
		DirectoryInfo corpus = new DirectoryInfo("CanterburyCorpus");
		archive.CreateEntries(corpus);
		// Create ZIP archive
		archive.Save(zipFile);
	}
}

Using FileInfo

Alternatively, use the FileInfo class to add files. This method loads the files using the FileInfo class and adds them to the ZIP archive with the Archive.CreateEntry(String, FileInfo) method. See the example below:

using Aspose.Zip;
using Aspose.Zip.Saving;
// Create FileStream for output ZIP archive
using (FileStream zipFile = File.Open("compress_directory.zip", FileMode.Create))
{
	using (Archive archive = new Archive(new ArchiveEntrySettings(null, new AesEcryptionSettings("p@s$", EncryptionMethod.AES128))))
	{
		// Add folder to archive
		DirectoryInfo corpus = new DirectoryInfo("CanterburyCorpus");
		archive.CreateEntries(corpus);
		// Create ZIP archive
		archive.Save(zipFile);
	}
}

Using File Path

You can also add files directly by providing their paths to the Archive.CreateEntry(String name, String path, Boolean openImmediately, ArchiveEntrySettings newEntrySettings) method. Here’s how to create a ZIP file in C#:

using Aspose.Zip;
using Aspose.Zip.Saving;
// Create FileStream for output ZIP archive
using (FileStream zipFile = File.Open("compress_directory.zip", FileMode.Create))
{
	using (Archive archive = new Archive(new ArchiveEntrySettings(null, new AesEcryptionSettings("p@s$", EncryptionMethod.AES128))))
	{
		// Add folder to archive
		DirectoryInfo corpus = new DirectoryInfo("CanterburyCorpus");
		archive.CreateEntries(corpus);
		// Create ZIP archive
		archive.Save(zipFile);
	}
}

Add Folders to a ZIP Archive in C#

Adding a folder to a ZIP archive is a convenient way to include multiple files. To zip files in C#, follow these steps:

  1. Create a FileStream object for the output ZIP archive.
  2. Instantiate the Archive class.
  3. Use the DirectoryInfo class to specify the folder to be zipped.
  4. Add the folder to the ZIP using the Archive.CreateEntries(DirectoryInfo) method.
  5. Save the ZIP archive with the Archive.Save(FileStream) method.

Here’s a code sample that demonstrates how to add a folder to a ZIP archive in C#:

using Aspose.Zip;
using Aspose.Zip.Saving;
// Create FileStream for output ZIP archive
using (FileStream zipFile = File.Open("compress_directory.zip", FileMode.Create))
{
	using (Archive archive = new Archive(new ArchiveEntrySettings(null, new AesEcryptionSettings("p@s$", EncryptionMethod.AES128))))
	{
		// Add folder to archive
		DirectoryInfo corpus = new DirectoryInfo("CanterburyCorpus");
		archive.CreateEntries(corpus);
		// Create ZIP archive
		archive.Save(zipFile);
	}
}

Create a Password Protected ZIP using ZipCrypto in C#

To enhance security, you can create password-protected ZIP archives using ZipCrypto encryption. This is achieved by using the ArchiveEntrySettings class in the constructor of the Archive, which allows you to specify the encryption type.

Here’s an example of how to create a password-protected ZIP archive using ZipCrypto in C#:

using Aspose.Zip;
using Aspose.Zip.Saving;
// Create FileStream for output ZIP archive
using (FileStream zipFile = File.Open("compress_directory.zip", FileMode.Create))
{
	using (Archive archive = new Archive(new ArchiveEntrySettings(null, new AesEcryptionSettings("p@s$", EncryptionMethod.AES128))))
	{
		// Add folder to archive
		DirectoryInfo corpus = new DirectoryInfo("CanterburyCorpus");
		archive.CreateEntries(corpus);
		// Create ZIP archive
		archive.Save(zipFile);
	}
}

Create Password Protected ZIP with AES Encryption

The Aspose.ZIP for .NET library also supports AES encryption for securing ZIP archives. You can choose from the following AES encryption methods:

  • AES128
  • AES192
  • AES256

To apply AES encryption, use the AesEcryptionSettings class. Here’s how to create a password-protected ZIP with AES encryption in C#:

using Aspose.Zip;
using Aspose.Zip.Saving;
// Create FileStream for output ZIP archive
using (FileStream zipFile = File.Open("compress_directory.zip", FileMode.Create))
{
	using (Archive archive = new Archive(new ArchiveEntrySettings(null, new AesEcryptionSettings("p@s$", EncryptionMethod.AES128))))
	{
		// Add folder to archive
		DirectoryInfo corpus = new DirectoryInfo("CanterburyCorpus");
		archive.CreateEntries(corpus);
		// Create ZIP archive
		archive.Save(zipFile);
	}
}

Set Parallel Compression Mode

For cases involving multiple entries, configure the API for parallel compression using the ParallelOptions class. Aspose.ZIP for .NET provides several parallel compression modes:

  • Never - Do not compress in parallel.
  • Always - Always compress in parallel (be cautious of out-of-memory issues).
  • Auto - Automatically decide whether to use parallel compression based on the entries.

Here’s an example demonstrating how to set the parallel compression mode while zipping multiple files:

using Aspose.Zip;
using Aspose.Zip.Saving;
// For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
string dataDir = "";
using (FileStream zipFile = File.Open(dataDir + "UsingParallelismToCompressFiles_out.zip", FileMode.Create))
{
    using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
    {
        using (FileStream source2 = File.Open(dataDir + "asyoulik.txt", FileMode.Open, FileAccess.Read))
        {
            using (var archive = new Archive())
            {
                archive.CreateEntry("alice29.txt", source1);
                archive.CreateEntry("asyoulik.txt", source2);
                //Define the parallelism criterion
                var parallelOptions = new Aspose.Zip.Saving.ParallelOptions
                {
                    ParallelCompressInMemory = ParallelCompressionMode.Always
                };
                archive.Save(zipFile,
                    new ArchiveSaveOptions()
                    {
                        ParallelOptions = parallelOptions,
                        Encoding = Encoding.ASCII,
                        ArchiveComment = "There are two poems from Canterbury corpus"
                    });
            }
        }
    }
}

Learn More About C# .NET ZIP Library

Dive deeper into our C# .NET ZIP API with the following resources:

Try ZIP Archives Online

Explore our free online application, based on Aspose.ZIP for .NET, to compress files into ZIP archives effortlessly.

Conclusion

In this article, you have learned how to programmatically create ZIP archives in C#. The provided code samples illustrate how to zip files in C#, add files and folders to ZIP archives, and create password-protected ZIP archives using both ZipCrypto and AES encryption methods. We also discussed parallel compression for efficiently handling large files and even touched upon how to zip files in .NET with C#. If you have any questions or need further assistance, feel free to reach out via our forum.

See Also

Unrar or Extract Files using C#Unzip Files in ZIP Archives using C#Create 7z (7-Zip) Archives in C# .NET
Open or Extract 7z (7zip) File in C# .NETCreate and Extract GZip Archives using C#Convert RAR Files to ZIP Archive in C#
Convert ZIP Archives to TAR in C#Create a Flat ZIP Archive in C#Create Executable Self-Extracting Archive in C#
Create TAR.GZ and TAR.XZ Files in C#Delete Files in a ZIP Archive in C#Extract Nested ZIP Archives in C#
Merge Multiple ZIP or TAR Archives in C#How to Create ZIP FilesExtract 7z Online

More in this category