[C#] Adding and Appending Files to an Existing ZIP File (ZipArchiveMode.Update)

To add new files to a ZIP file that has already been created, or to update existing files, open the file using the ZipFile.Open method with ZipArchiveMode.Update. Once the ZipArchive object is opened in this mode, you can easily add files by calling CreateEntryFromFile.


目次

Implementation Sample: Adding a File to an Archive

The following code adds a file named “Readme.txt” to an existing ZIP file called “Backup.zip”.

Sample Code

using System;
using System.IO;
using System.IO.Compression; // Note: System.IO.Compression.FileSystem may be required in some environments

public class Program
{
    public static void Main()
    {
        // 1. Prepare the test environment
        // Create a base ZIP file and a file to add
        string zipPath = "Backup.zip";
        string fileToAdd = "Readme.txt";

        // Create an empty ZIP file for this demonstration
        if (File.Exists(zipPath)) File.Delete(zipPath);
        using (ZipFile.Open(zipPath, ZipArchiveMode.Create)) { /* Create as empty */ }

        // Create the file to be added
        File.WriteAllText(fileToAdd, "This is the file to be added.");

        Console.WriteLine($"Before processing: Verified {zipPath}.");

        try
        {
            // 2. Open the ZIP file in "Update mode"
            // ZipArchiveMode.Update: Allows both reading and writing
            using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
            {
                // 3. Add the file to the archive
                // CreateEntryFromFile(File to add, Filename inside the ZIP)
                // Note: You can also specify CompressionLevel as the third argument
                archive.CreateEntryFromFile(fileToAdd, "Docs/Readme.txt");
                
                // Tip: Use archive.CreateEntry() if you want to write manually using a Stream
            }

            Console.WriteLine("File addition complete.");

            // (Verification) Display the contents
            using (ZipArchive archive = ZipFile.OpenRead(zipPath))
            {
                Console.WriteLine("\n--- Contents of the ZIP file ---");
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    Console.WriteLine(entry.FullName);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

Execution Result

Before processing: Verified Backup.zip.
File addition complete.

--- Contents of the ZIP file ---
Docs/Readme.txt

Explanation and Technical Points

1. ZipArchiveMode.Update

This is the mode passed as the second argument to ZipFile.Open:

  • Create: Creates a new file (overwrites if it already exists).
  • Read: Opens the file as read-only.
  • Update: Maintains the existing content and allows adding or deleting entries.

2. CreateEntryFromFile vs CreateEntry

  • CreateEntryFromFile: Adds a file from the disk to the ZIP with a single line of code. This is the recommended approach for simple file addition.
  • CreateEntry: Creates an empty entry (a placeholder inside the ZIP). You then get a stream using entry.Open() to write strings or data from memory. This is used for more manual operations.

3. Hierarchical Structure inside the ZIP

By specifying a path separated by forward slashes (e.g., "Docs/Readme.txt") in the second argument of CreateEntryFromFile, you can create a folder structure inside the ZIP file.

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

この記事を書いた人

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

目次