How to extract and compress files with System.IO.Compression.ZipArchive in C #?

5

I'm starting in C #. I saw that it has the class System.IO.Compression.ZipArchive to work with zip files.

I have some doubts:

  • How do I unzip an existing zip through ZipArchive?

  • How do I compress to an existing zip file? That is, add files to an existing ZIP.

  • How to create a new ZIP file (from scratch)? For example, I want to create a new ZIP file through C # and add existing files in this ZIP.

asked by anonymous 19.07.2017 / 16:45

1 answer

6

In the first two cases you need to be aware that you need to "open" the zip file and always you need to release the resources using Dispose() ( using calls the method automatically).

Unzip an existing zip

Use the ExtractToDirectory() . Pass the path where you want to unpack the files as a parameter. All entries in the zip file will be unzipped in this directory.

string caminhoZip = @"C:\Users\LINQ\arquivo.zip";
string pastaExtrair = @"C:\Users\LINQ\extrair-aqui";

using (ZipArchive zip = ZipFile.Open(caminhoZip))
{
    zip.ExtractToDirectory(pastaExtrair);
} 

Add files to an existing zip.

Use the CreateEntryFromFile() . The first parameter should be the path of the file you want to add and the second parameter is the name of this file inside the zip. Note that ZipArchiveMode.Update must be passed as the second parameter of ZipFile.Open() .

string caminhoZip = @"C:\Users\LINQ\arquivo.zip";        
string novo = @"C:\Users\LINQ\novo.txt";

using (ZipArchive zip = ZipFile.Open(caminhoZip, ZipArchiveMode.Update))
{
    zip.CreateEntryFromFile(novo, "novo.txt");            
} 

Create a new ZIP file

  • If you want to zip a folder

    Use ZipFile.CreateFromDirectory() . The first parameter is the folder you want to zip and the second is the path of the new file to be created. If you want to create an empty zip file just create it from an empty folder.

    string pastaParaZipar = @"C:\Users\LINQ\pasta-zip";
    string caminhoZip = @"C:\Users\LINQ\arquivo-novo.zip";    
    
    ZipFile.CreateFromDirectory(pastaParaZipar, caminhoZip);
    
  • If you prefer to create a file and go adding items to it

    Use ZipFile.Open() , passing ZipArchiveMode.Create as second parameter.

    string nomeArquivo = @"C:\Users\LINQ\arquivo.zip";
    
    using (ZipArchive zip = ZipFile.Open(nomeArquivo, ZipArchiveMode.Create))
    {
        // Adicione arquivos...
    }
    
  • 19.07.2017 / 16:53