We have two new classes, ZipArchive
and ZipArchiveEntry
, which add the capability to create .zip archives to the .NET framework. This was possible previously, but with several limitations.
Next we will see how to use the ZipArchive
class to create a Zip file and to extract it to a concrete location.
caZipArchive
.System.IO.Compression
and System.IO.Compression.Filesystem
assemblies as references to the project.using
clauses:using System.IO; using System.IO.Compression;
static void CreateZipFile() { String ZipPath= @"C:PACKT 2-CLRcaZipArchive est"; String ZipFilePath = ZipPath + "test.zip"; String FileName01 = "OneTextDocument.txt"; String FileName02 = "OtherTextDocument.txt"; String FileToZip01 = ZipPath + FileName01; String FileToZip02 = ZipPath + FileName02; using (FileStreamZipToOpen = new FileStream(ZipFilePath, FileMode.CreateNew)) { using (ZipArchiveZArchive = new ZipArchive(ZipToOpen,ZipArchiveMode.Create)) { ZArchive.CreateEntryFromFile(FileToZip01, FileName01); ZArchive.CreateEntryFromFile(FileToZip02, FileName02); } } }
Main
method and execute the application. We should see that a Zip file has been created for us.static void ExtractZipFile() { String ZipPath = @"C:PACKT 2-CLRcaZipArchive est"; String ZipFilePath = ZipPath + "test.zip"; String ExtractionPath = @"C:PACKT 2-CLRcaZipArchive estunzip"; using (ZipArchiveZArchive = ZipFile.OpenRead(ZipFilePath)) { foreach (ZipArchiveEntry zaEntry in ZArchive.Entries) { zaEntry.ExtractToFile(Path.Combine(ExtractionPath, zaEntry.FullName)); } } }
Main
method, just after CreateZipFile
:static void Main(string[] args) { //First we create the zip file CreateZipFile(); //Next, we extract it ExtractZipFile(); }
We used FileStream
to create a new file stream and write to it with ZipArchive
.
Additionally, we added two files using the CreateEntryFromFile
extension method of the ZipArchive
class that is the result of adding the System.IO.Compression.FileSystem
assembly.
With this we had our ZIP file created.
Continuing, we opened our ZIP file using the OpenRead
method of the ZipFile
class, which returns a ZipArchive
object that represents the package of compressed files.
We can iterate all the entries with a simple foreach
instruction. For each ZipArchiveEntry
, we extract it with the ExtractToFile
extension method.
And that's it! In a few lines of code we have created a ZIP file, added some files, and then extracted the ZIP files to another folder.
We could also specify the level of compression, edit the files within the ZIP file, or update existing ZIP files.
Additionally, for simplicity we 'neither validated for the existence of files or directories nor checked for any errors, so we should do this properly in a production environment.
We should be aware that the extension methods (provided by the System.IO.Compression.FileSystem
assembly) that we used aren't available in Windows Store apps. There we should compress and decompress using the GZipStream
or DeflateStream
class.