Zip and unzip files

25,394

Solution 1

If you're using Visual Studio 2012 and the .NET Framework 4.5 you can use the new compression library:

//This stores the path where the file should be unzipped to,
//including any subfolders that the file was originally in.
string fileUnzipFullPath;

//This is the full name of the destination file including
//the path
string fileUnzipFullName;

//Opens the zip file up to be read
using (ZipArchive archive = ZipFile.OpenRead(zipName))
{
    //Loops through each file in the zip file
    foreach (ZipArchiveEntry file in archive.Entries)
    {
        //Outputs relevant file information to the console
        Console.WriteLine("File Name: {0}", file.Name);
        Console.WriteLine("File Size: {0} bytes", file.Length);
        Console.WriteLine("Compression Ratio: {0}", ((double)file.CompressedLength / file.Length).ToString("0.0%"));

        //Identifies the destination file name and path
        fileUnzipFullName = Path.Combine(dirToUnzipTo, file.FullName);

        //Extracts the files to the output folder in a safer manner
        if (!System.IO.File.Exists(fileUnzipFullName))
        {
            //Calculates what the new full path for the unzipped file should be
            fileUnzipFullPath = Path.GetDirectoryName(fileUnzipFullName);

            //Creates the directory (if it doesn't exist) for the new path
            Directory.CreateDirectory(fileUnzipFullPath);

            //Extracts the file to (potentially new) path
            file.ExtractToFile(fileUnzipFullName);
        }
    }
}

Solution 2

Unanswered, although a while ago, so I'll still put my $0.02 in there for anyone else who hits this on keywords...

VB 2012 (.Net 4.5) added new features to System.IO.Compression (System.IO.Compression.FileSystem.dll) that will do what you want. We only had GZip before. You can still use the free DotNetZip or SharpZipLib, of course.

The ZipFile class has 2 static methods that make simple compression/decompression drop-dead simple: CreateFromDirectory and ExtractToDirectory. Yo also have compression choices of NoCompression, Fastest, and Optimal.

One thing about it that struck me about your post was the concept of files (even archives) within archives. With the ZipArchive and ZipArchiveEntry classes you can now

ZipArchive:

Using zippedFile as ZipArchive = ZipFile.Open("foo.zip", ZipArchiveMode.Read)
    For Each ntry as ZipArchiveEntry In zippedFile.Entries
        Debug.Writeline("entry " & ntry.FullName & " is only " & ntry.CompressedLength.ToString)
    Next
End Using

Your question also was about adding to an existing archive. You can now do that like this:

Using zippedFile as ZipArchive = ZipFile.Open("foo.zip", ZipArchiveMode.Update)
    zippedFile.createEntry("bar.txt", CompressionLevel.Fastest)
    ' likewise you can get an entry already in there...
    Dim ntry As ZipArchiveEntry = zippedFile.GetEntry("wtf.doc")
    ' even delete an entry without need to decompress & compress again!
    ntry.Delete() ' !
End Using

Again, this was a while ago, but a lot of us still use 2012, and as this change won't be going anywhere in future versions, it should still prove helpful moving forward if anyone hits in on a keyword/tag search...

...and we didn't even talk about UTF-8 support!

Solution 3

You probably aren't referencing System.IO.Compression. Check the box for that assembly reference and it should eliminate the error.

Solution 4

As mentioned in https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile(v=vs.110).aspx

You can use ZipFile.ExtractToDirectory and CreateFromDirectory

This is the example:

Imports System.IO

Imports System.IO.Compression

Module Module1

Sub Main()

   Dim startPath As String = "c:\example\start"
   Dim zipPath As String = "c:\example\result.zip"
   Dim extractPath As String = "c:\example\extract"

   ZipFile.CreateFromDirectory(startPath, zipPath)
   ZipFile.ExtractToDirectory(zipPath, extractPath)

End Sub

End Module

Make sure you have referenced System.IO.Compression.FileSystem for using this function.

Share:
25,394
Darryl Janecek
Author by

Darryl Janecek

Updated on July 09, 2022

Comments

  • Darryl Janecek
    Darryl Janecek almost 2 years

    I am a programmer using VS2012. I am wanting to unzip a zip file (made with Winzip, filzip or other zip compression routines) and then also be able to zip the files back up into a zip file.

    What is the best library to use for this and can I please have some sample code on how to use the library?

    EDIT

    I am using VB.net, here is my code:

    Public Function extractZipArchive() As Boolean
        Dim zipPath As String = "c:\example\start.zip"
        Dim extractPath As String = "c:\example\extract"
    
        Using archive As ZipArchive = ZipFile.OpenRead(zipPath)
            For Each entry As ZipArchiveEntry In archive.Entries
                If entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) Then
                    entry.ExtractToFile(Path.Combine(extractPath, entry.FullName))
                End If
            Next
        End Using
    End Function
    

    What import statements do I need to use? Currently I have added the following:

    Imports System.IO
    Imports System.IO.Compression
    

    I am getting the error:

    Type 'ZipArchive' is not defined

    How can I fix this error?