Remove File from ZIP in C#

This simple article covers how to remove file from ZIP in C#. It contains all the information, like the algorithm, as well as a runnable code snippet to delete ZIP file in C#. Furthermore, you do not need to install any ZIP-related utility to work with this feature in your environment.

Steps to Delete File From ZIP in C#

  1. Prepare the environment by downloading Aspose.ZIP on your end
  2. Create an instance of the Archive class to access the source directory
  3. Iterate each entry in the directory and get the files matching the required conditions
  4. Remove all the files in the filtered list by invoking the DeleteEntry method
  5. Export the output ZIP directory

The steps above present the overview to delete file from ZIP in C#. It starts the process by compiling an array list of all the files that contain specific file names. Then it deletes all such files by iterating through the populated list and proceeds to export the output ZIP directory to the disk or a stream as per your requirements.

Code to Delete ZIP File in C#

// Load the ZIP archive
using (var archive = new Archive("archive.zip"))
{
// List to keep files to be deleted
List<ArchiveEntry> entriesToDelete = new List<ArchiveEntry>();
// Loop through ZIP entries
foreach (ArchiveEntry entry in archive.Entries)
{
// Add file/folder into list
if (entry.Name.ToLower().Contains("source"))
{
entriesToDelete.Add(entry);
}
}
// Delete all listed entries
foreach (var entry in entriesToDelete)
{
archive.DeleteEntry(entry);
}
// Save updated archive
archive.Save("updated-archive.zip");
}

This sample code shows how to remove a ZIP file in C#. At the same time, it can be enhanced to remove any specific file in the directory even when you do not know the file names like targeting the ZIP entries using the index position number to delete the specific compressed files.

This guide has explained how to delete zipped files in C#. Besides, if you want to make a ZIP file from scratch, then visit the tutorial on Create ZIP in C#.