[C#] Extracting a Specific File from a ZIP Archive (ExtractToFile)

Sometimes, instead of extracting every file in a ZIP archive, you may want to search for and extract only one specific file. By using the ExtractToFile method of the ZipArchiveEntry class, you can write the retrieved entry (file information) directly to a specified path as a file.

目次

Implementation Sample: Extracting a Specific Log from a Log Archive

The following code searches for a specific error log file (Error_2025.txt) within a ZIP file (Logs.zip) and extracts only that file.

Sample Code

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

public class Program
{
    public static void Main()
    {
        string zipPath = "Logs.zip";
        
        // Path inside the ZIP (If it's in a folder, specify like "logs/error.txt")
        string targetEntryName = "Error_2025.txt";
        
        // Output path for the extracted file
        string outputPath = "Extracted_ErrorLog.txt";

        // 1. Prepare test environment (Create ZIP file)
        if (File.Exists(zipPath)) File.Delete(zipPath);
        using (var archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
        {
            archive.CreateEntryFromFile(CreateDummyFile("System.log"), "System.log");
            archive.CreateEntryFromFile(CreateDummyFile("Error_2025.txt"), targetEntryName);
        }

        try
        {
            // 2. Open the ZIP file in Read mode
            using (ZipArchive archive = ZipFile.OpenRead(zipPath))
            {
                // 3. Get the entry with the specified name
                ZipArchiveEntry entry = archive.GetEntry(targetEntryName);

                if (entry != null)
                {
                    Console.WriteLine($"File found. Size: {entry.Length} bytes");

                    // 4. Extract (save) as a file
                    // Use overwrite: true to allow overwriting existing files
                    entry.ExtractToFile(outputPath, overwrite: true);

                    Console.WriteLine($"Extraction complete: {Path.GetFullPath(outputPath)}");
                }
                else
                {
                    Console.WriteLine($"Error: {targetEntryName} does not exist in the archive.");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }

    // Helper to create a dummy file
    static string CreateDummyFile(string name)
    {
        File.WriteAllText(name, "Log content...");
        return name;
    }
}

Execution Result

File found. Size: 14 bytes
Extraction complete: C:\Work\Extracted_ErrorLog.txt

Explanation and Technical Points

1. ZipArchiveEntry.ExtractToFile

This method writes the content of an entry to a file at a specified path. You do not need to manually open a stream and use CopyTo to move data, which makes the implementation very simple.

// (Traditional approach) Using streams
// using (var reader = entry.Open())
// using (var writer = File.OpenWrite(outputPath))
// {
//     reader.CopyTo(writer);
// }

// (Recommended) Using ExtractToFile
entry.ExtractToFile(outputPath, overwrite: true);

2. Searching for an Entry (GetEntry)

The archive.GetEntry("path") method searches for an entry that exactly matches the specified path, including case sensitivity. If you want to search while ignoring case (e.g., matching both readme.txt and README.TXT), you should search using LINQ against archive.Entries.

// Example of searching while ignoring case
var entry = archive.Entries.FirstOrDefault(e => 
    e.FullName.Equals(targetEntryName, StringComparison.OrdinalIgnoreCase));
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次