Search code examples
c#dotnetzip

Auto Extract a zip file


I'm trying make a program that extracts a specific zip file everytime the program launches.

this is my code to create the zip file:

//creating the file
ZipFile File = new ZipFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ABCD.zip");

//Adding files

File.AddFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ab.dat", "");
File.AddFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\cd.dat", "");

//Save the file
File.Save();

I want to Extract the files ab.dat and cd.dat from ABCD.zip to the .exe file directory automatically.

Thanks for helping.


Solution

  • Taken mostly from the DotNetZip documentation:

    private void Extract()
    {
        //Zip Location
        string zipToUnpack = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ABCD.zip";
        // .EXE Directory
        string unpackDirectory = System.IO.Path.GetDirectoryName(
            System.Reflection.Assembly.GetExecutingAssembly().Location);
    
        using (ZipFile zip = ZipFile.Read(zipToUnpack))
        {
            foreach (ZipEntry e in zip)
            {
                 //If filename matches
                 if (e.FileName == "ab.dat" || e.FileName == "cd.dat")
                     e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
            }
        }
    }
    

    You can also filter the results using ExtractSelectEntries by selecting the files there:

    zip.ExtractSelectedEntries("name = 'ab.dat' OR name = 'cd.dat'", "\", unpackDirectory, ExtractExistingFileAction.OverwriteSilently)
    

    Or selecting all .dat files with a wildcard

    zip.ExtractSelectedEntries("name = '*.dat'", "\", unpackDirectory, ExtractExistingFileAction.OverwriteSilently)
    

    Use each ZipEntry's FileName property to see if it has the name you would like to extract.