[C#] Deleting a Specific File in a ZIP File (ZipArchiveEntry.Delete)

Sometimes, after creating a ZIP archive, you may want to remove only specific files. For example, you might have included log files by mistake or want to exclude old configuration files from the archive.

To perform this operation, you must open the ZIP file using ZipArchiveMode.Update, retrieve the specific entry, and call the Delete() method.

目次

Implementation Sample: Deleting Unnecessary Temporary Files

The following code searches for an unnecessary file named “temp.dat” inside a ZIP file and deletes it if it exists.

Sample Code

using System;
using System.IO;
using System.IO.Compression;

public class Program
{
    public static void Main()
    {
        string zipPath = "ProjectArchive.zip";
        string targetFileName = "temp.dat";

        // 1. Prepare test environment
        // Create a ZIP file and include the file to be deleted
        if (File.Exists(zipPath)) File.Delete(zipPath);
        
        using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
        {
            archive.CreateEntryFromFile("main.exe", "main.exe"); // Dummy file
            // This is the file to be deleted
            ZipArchiveEntry entry = archive.CreateEntry(targetFileName); 
        }

        Console.WriteLine("--- ZIP contents before processing ---");
        ShowZipContents(zipPath);


        // 2. Process to delete a file from the ZIP archive
        try
        {
            // It is mandatory to open with ZipArchiveMode.Update
            using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
            {
                // Retrieve the file to be deleted by its path (name)
                // Note: Paths inside ZIP files are generally case-sensitive
                ZipArchiveEntry entry = archive.GetEntry(targetFileName);

                if (entry != null)
                {
                    // Delete the entry (file)
                    entry.Delete();
                    Console.WriteLine($"\nDeleted: {targetFileName}");
                }
                else
                {
                    Console.WriteLine($"\nFile not found: {targetFileName}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }

        Console.WriteLine("\n--- ZIP contents after processing ---");
        ShowZipContents(zipPath);
    }

    // Helper method to display ZIP contents
    static void ShowZipContents(string path)
    {
        using (ZipArchive archive = ZipFile.OpenRead(path))
        {
            foreach (var e in archive.Entries)
            {
                Console.WriteLine($" - {e.FullName}");
            }
        }
    }
}

Execution Result

--- ZIP contents before processing ---
 - main.exe
 - temp.dat

Deleted: temp.dat

--- ZIP contents after processing ---
 - main.exe

Explanation and Technical Points

1. ZipArchiveMode.Update

To delete a file, you must open the archive in Update mode because the archive itself needs to be rewritten. You cannot delete files in Read mode.

2. Behavior of GetEntry

archive.GetEntry("path") returns a ZipArchiveEntry object if the specified file exists in the ZIP, and returns null if it does not. It is important to perform a null check as shown in the sample code to avoid a NullReferenceException.

3. Specifying Directory Hierarchy

If you want to delete a file in a subfolder within the ZIP, you must include the path. Example: archive.GetEntry("logs/error.log"). In ZIP files created in Windows environments, the delimiter might sometimes be a backslash (\), so be careful when specifying the path (generally, the forward slash / is recommended).

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次