【问题标题】:How to extract just the specific directory from a zip archive in C# .NET 4.5?如何从 C# .NET 4.5 中的 zip 存档中仅提取特定目录?
【发布时间】:2025-12-31 23:00:01
【问题描述】:

我有以下内部结构的 zip 文件:

file1.txt
directoryABC
    fileA.txt
    fileB.txt
    fileC.txt

将文件从“directoryABC”文件夹提取到硬盘上的目标位置的最佳方法是什么?例如,如果目标位置是“C:\temp”,那么它的内容应该是:

temp
    directoryABC
        fileA.txt
        fileB.txt
        fileC.txt

此外,在某些情况下,我只想提取“directoryABC”的内容,因此结果将是:

temp
    fileA.txt
    fileB.txt
    fileC.txt

如何在 C# .NET 4.5 中使用 System.IO.Compression 中的类来实现这一点?

【问题讨论】:

    标签: c# .net compression zip


    【解决方案1】:

    这是另一个将命名目录的文件提取到目标目录的版本...

    class Program
    {
        static object lockObj = new object();
    
        static void Main(string[] args)
        {
            string zipPath = @"C:\Temp\Test\Test.zip";
            string extractPath = @"c:\Temp\xxx";
            string directory = "testabc";
            using (ZipArchive archive = ZipFile.OpenRead(zipPath))
            {
                var result = from currEntry in archive.Entries
                             where Path.GetDirectoryName(currEntry.FullName) == directory
                             where !String.IsNullOrEmpty(currEntry.Name)
                             select currEntry;
    
    
                foreach (ZipArchiveEntry entry in result)
                {
                    entry.ExtractToFile(Path.Combine(extractPath, entry.Name));
                }
            } 
        }        
    }
    

    【讨论】:

    • 请注意,为了使用ZipFile,使用的是System.IO.Compression,但所需的程序集是System.IO.Compression.FileSystemdocumentation 声明正确,但我很难找到它。