Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract just the specific directory from a zip archive in C# .NET 4.5?

I have zip file with following internal structure:

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

What would be the best way to extract files from "directoryABC" folder to a target location on hard drive? For example if target location is "C:\temp" then its content should be:

temp
    directoryABC
        fileA.txt
        fileB.txt
        fileC.txt

Also in certain situations I'd want to extract only content of the "directoryABC" so the result would be:

temp
    fileA.txt
    fileB.txt
    fileC.txt

How can I accomplish this by using classes from System.IO.Compression in C# .NET 4.5?

like image 759
matori82 Avatar asked Mar 02 '14 20:03

matori82


1 Answers

This is another version to extract the files of a named directory to the target directory...

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));
            }
        } 
    }        
}
like image 71
embee Avatar answered Nov 02 '22 18:11

embee