[C#] Extracting (Unzipping) a ZIP File (ZipFile.ExtractToDirectory)

To extract all files within a ZIP archive to a specific folder, use the ExtractToDirectory method of the System.IO.Compression.ZipFile class. This method is very convenient because it automatically creates the destination folder if it does not exist.

目次

Table of Contents

  • Implementation Sample: Extracting All Files from an Archive
  • Sample Code
  • Execution Result
  • Explanation and Notes
    1. Automatic Directory Creation
    2. Filename Conflicts
    3. Overwriting Files (.NET Core / .NET 5+ or later)
    4. Character Encoding Issues

Implementation Sample: Extracting All Files from an Archive

The following code extracts a ZIP file named Archive.zip into a folder named Output.

Sample Code

using System;
using System.IO;
using System.IO.Compression; // Reference may be required

public class Program
{
    public static void Main()
    {
        string zipPath = "Archive.zip";
        string extractPath = "./Output";

        // 1. Prepare the test environment
        // Create a dummy ZIP file to test extraction
        if (File.Exists(zipPath)) File.Delete(zipPath);
        if (Directory.Exists(extractPath)) Directory.Delete(extractPath, recursive: true);

        // Create a dummy ZIP (generate ZIP from a memory entry)
        using (var archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
        {
            var entry = archive.CreateEntry("memo.txt");
            using (var writer = new StreamWriter(entry.Open()))
            {
                writer.Write("This is a file for extraction testing.");
            }
        }
        Console.WriteLine($"Prepared ZIP file: {zipPath}");


        try
        {
            Console.WriteLine($"Extraction folder: {extractPath}");

            // 2. Extract the ZIP file to the specified folder
            // ZipFile.ExtractToDirectory(path to ZIP file, destination folder path)
            ZipFile.ExtractToDirectory(zipPath, extractPath);

            Console.WriteLine("Extraction complete.");

            // (Verification) Display the extracted files
            string[] files = Directory.GetFiles(extractPath);
            foreach (var file in files)
            {
                Console.WriteLine($" - Extracted file: {file}");
            }
        }
        catch (IOException ex)
        {
            // Occurs if a file with the same name already exists in the destination folder
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Execution Result

Prepared ZIP file: Archive.zip
Extraction folder: ./Output
Extraction complete.
 - Extracted file: ./Output\memo.txt

Explanation and Notes

1. Automatic Directory Creation

The ExtractToDirectory method automatically creates the destination directory (folder) specified in the second argument if it does not already exist.

2. Filename Conflicts

If a file with the same name as one inside the ZIP file already exists in the destination directory, a System.IO.IOException is thrown, and the process stops. Files are not overwritten by default.

3. Overwriting Files (.NET Core / .NET 5+ or later)

In modern .NET environments, an overloaded method is available that allows you to specify overwrite: true as the third argument.

// Force extraction by overwriting existing files
ZipFile.ExtractToDirectory(zipPath, extractPath, overwrite: true);

4. Character Encoding Issues

When extracting a ZIP file created on Windows (using Shift-JIS) on Mac or Linux, or vice versa, filenames may become garbled. In such cases, use the overload that allows you to specify the Encoding.

// Example of extracting by specifying Shift-JIS (cp932)
// Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // If necessary
ZipFile.ExtractToDirectory(zipPath, extractPath, Encoding.GetEncoding("Shift_JIS"));
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次