如何在C# .NET 4.5中从zip压缩文件中仅提取特定目录?

15

我有一个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类来完成此任务?

1个回答

19

这是另一种将指定目录的文件提取到目标目录的方法...

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));
            }
        } 
    }        
}

3
请注意,要使用ZipFile,需要使用System.IO.Compression,但必须引用System.IO.Compression.FileSystem程序集。文档中已经说明了这一点,但我曾经在查找时遇到了困难。 - David Diez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接