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...
}