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
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);
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...
}
If the downvote crowd has any clarification, you’re welcome.
– Wallace Maxters