How to extract and compress files with System.IO.Compression.Ziparchive in c#?

Asked

Viewed 2,702 times

6

I’m starting in C#. I saw that there’s class System.IO.Compression.ZipArchive to work with zip files.

I have some doubts:

  • How do I unzip an existing zip via 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.

  • 4

    If the downvote crowd has any clarification, you’re welcome.

1 answer

6


In the first two cases you need to note that it is necessary to "open" the zip file and at all times it is necessary to release the resources using the Dispose() (the using calls the method automatically).

Unzip an existing zip

Use the method ExtractToDirectory(). Pass as parameter the path you want to unpack the files in. All zip file entries 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 method CreateEntryFromFile(). The first parameter should be the file path you want to add and the second parameter is the name of this file inside the zip. Note that it is necessary to pass ZipArchiveMode.Update 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

  1. If you want to zip a briefcase

    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);
    
  2. If you prefer to create a file and go adding items to it

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.