DotNetZip - C# Examples
Here are a bunch of examples in C# that illustrate how to use the library.
There are a few complete, working example applications shipped in the source code distribution.
Create a zip file, and add items to it.
1using (ZipFile zip = new ZipFile()) 2{ 3 zip.AddFile("ReadMe.txt"); 4 zip.AddFile("Resume.doc"); 5 zip.AddFile("Portrait.png"); 6 zip.Save("Package.zip"); 7}
Add items to a zip file, using Zip 2.0 encryption, and the same password for all items.
1using (ZipFile zip = new ZipFile()) 2{ 3 zip.Password= "123456!"; 4 zip.AddFile("ReadMe.txt"); 5 zip.AddFile("7440-N49th.png"); 6 zip.AddFile("2005_Annual_Report.pdf"); 7 zip.Save("Backup.zip"); 8}
Add files to a zip file, using Zip 2.0 encryption, and different passwords for different files.
1using (ZipFile zip = new ZipFile()) 2{ 3 zip.AddFile("ReadMe.txt"); // no password for this one 4 zip.Password= "123456!"; 5 zip.AddFile("7440-N49th.png"); 6 zip.Password= "!Secret1"; 7 zip.AddFile("2005_Annual_Report.pdf"); 8 9 zip.Save("Backup.zip"); 10}
Create a zip archive, and add files to it, using WinZip-compatible AES 256-bit encryption for one of the files.
1using (ZipFile zip = new ZipFile()) 2{ 3 zip.AddFile("ReadMe.txt"); // no password for this one 4 zip.Password= "Cool.Hand.Luke!"; 5 zip.Encryption= EncryptionAlgorithm.WinZipAes256; 6 zip.AddFile("Rawdata-2008-12-18.csv"); 7 zip.Save("Backup-AES-Encrypted.zip"); 8}
Create a zip, and add a file, telling the library to not use compression when adding in the file. This makes sense with previously-compressed files such as those in .mp3 format. The Deflate algorithm can actually increase the size of a data stream that has already been compressed. The DotNetZip library intelligently turns off compression for those files that get bigger with compression, but the ForceNoCompression property allows you to do it explicitly.
1using (ZipFile zip = new ZipFile()) 2{ 3 zip.ForceNoCompression = true; 4 zip.AddFile(@"MyMusic\Handel\Messiah-01.mp3"); 5 zip.Save(ZipFileToCreate); 6}
Zip up an entire directory, recursively. Use unicode to encode entries in the archive, for those files in that directory tree that have characters outside the ANSI range. Finally, specify a comment on the zip archive when creating it. (Be careful using Unicode - it is not widely supported by other zip utilities)
1using (ZipFile zip = new ZipFile()) 2{ 3 zip.UseUnicode= true; // utf-8 4 zip.AddDirectory(@"MyDocuments\ProjectX"); 5 zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ; 6 zip.Save(ZipFileToCreate); 7}
Zip up an entire directory, recursively. Use the "big5" encoding for those files in that directory tree that have chinese characters.
1using (ZipFile zip = new ZipFile()) 2{ 3 zip.Encoding = System.Text.Encoding.GetEncoding("big5"); // chinese 4 zip.AddDirectory(@"MyDocuments\ProjectX"); 5 zip.Save(ZipFileToCreate); 6}
Zip up an file, using the ZIP64 extensions if necessary to support large files.
1using (ZipFile zip = new ZipFile()) 2{ 3 zip.UseZip64WhenSaving = Zip64Option.AsNecessary; 4 zip.AddFile(@"RawData-HugeFile-13800.dat"); 5 zip.Save(ZipFileToCreate); 6}
Zip up a set of files, each protected by the same password. Also, explicitly override the last modified time for all of the files as they are stored in the zip archive.
1<hr/> 2 3<p>Zip up a set of files and directories, and re-map them into a 4different directory hierarchy in the zip file.</p> 5 6<pre lang="cs" numberLines="true" outlining="true" 7 title="remap directories"> 8 using (ZipFile zip = new ZipFile()) 9 { 10 // files in the filesystem like MyDocuments\ProjectX\File1.txt , will be stored in the zip archive as backup\File1.txt 11 zip.AddDirectory(@"MyDocuments\ProjectX", "backup"); 12 // files in the filesystem like MyMusic\Santana\OyeComoVa.mp3, will be stored in the zip archive as tunes\Santana\OyeComoVa.mp3 13 zip.AddDirectory("MyMusic", "tunes"); 14 // The Readme.txt file in the filesystem will be stored in the zip archive as documents\Readme.txt 15 zip.AddDirectory("Readme.txt", "documents"); 16 17 zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ; 18 zip.Save(ZipFileToCreate); 19 }
Add content obtained from a stream (MemoryStrean, FileStream, etc) into a zip archive. Also, add a comment to the entry that was added from the stream.
1using (ZipFile zip = new ZipFile()) 2{ 3 ZipEntry e= zip.AddEntry("Content-From-Stream.bin", StreamToRead); 4 e.Comment = "The content for entry in the zip file was obtained from a stream"; 5 zip.AddFile("Readme.txt"); 6 zip.Save(ZipToCreate); 7}
Open an existing zip file, remove an entry from it, and save the archive. This was first supported in v1.5 of the library.
1using (ZipFile zip = ZipFile.Read(ExistingZipFile)) 2{ 3 // use the indexer to remove the file from the zip archive 4 zip["Readme.txt"] = null; 5 zip.Comment = "This archive has been modified from its original version. Some files have been removed."; 6 zip.Save(); 7}
Open an existing zip file, rename an entry, then save it. This was first supported in v1.7 of the library.
1int renameCount = 0; 2using (ZipFile zip2 = ZipFile.Read(ExistingZipFile)) 3{ 4 foreach (ZipEntry e in zip2) 5 { 6 if (e.FileName.EndsWith(".txt")) 7 { 8 var newname = "renamed_files\\" + e.FileName; 9 10 e.FileName = newname; 11 e.Comment = "renamed"; 12 renameCount++; 13 } 14 } 15 zip2.Comment = String.Format("This archive has been modified. {0} files have been renamed.", renameCount); 16 zip2.Save(); 17}
Extract all files from a zip archive:
1using (ZipFile zip = ZipFile.Read(ExistingZipFile)) 2{ 3 foreach (ZipEntry e in zip) 4 { 5 e.Extract(TargetDirectory); 6 } 7}
The default behavior of extraction is to NOT overwrite existing files. In this example, the app Extracts all files, and overwrites existing files in the filesystem:
1using (ZipFile zip = ZipFile.Read(ExistingZipFile)) 2{ 3 foreach (ZipEntry e in zip) 4 { 5 e.Extract(TargetDirectory, true); // overwrite == true 6 } 7}
Extract an entry from the zip archive into a previously-opened stream:
1using (ZipFile zip = ZipFile.Read(ExistingZipFile)) 2{ 3 ZipEntry e = zip["MyReport.doc"]; 4 e.Extract(OutputStream); 5}
Extract an Entry that was encrypted with a password, into the specified base directory:
1using (ZipFile zip = ZipFile.Read(ExistingZipFile)) 2{ 3 ZipEntry e = zip["TaxInformation-2008.xls"]; 4 e.ExtractWithPassword(BaseDirectory, Password); 5}
List all the entries in a zip file:
1using (ZipFile zip = ZipFile.Read(ExistingZipFile)) 2{ 3 foreach (ZipEntry e in zip) 4 { 5 if (header) 6 { 7 System.Console.WriteLine("Zipfile: {0}", zip.Name); 8 if ((zip.Comment != null) && (zip.Comment != "")) 9 System.Console.WriteLine("Comment: {0}", zip.Comment); 10 System.Console.WriteLine("\n{1,-22} {2,8} {3,5} {4,8} {5,3} {0}", 11 "Filename", "Modified", "Size", "Ratio", "Packed", "pw?"); 12 System.Console.WriteLine(new System.String('-', 72)); 13 header = false; 14 } 15 System.Console.WriteLine("{1,-22} {2,8} {3,5:F0}% {4,8} {5,3} {0}", 16 e.FileName, 17 e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"), 18 e.UncompressedSize, 19 e.CompressionRatio, 20 e.CompressedSize, 21 (e.UsesEncryption) ? "Y" : "N"); 22 23 } 24}
Read in zip archive content from a stream, and extract the content for one entry to another stream. In this example, the filename "NameOfEntryInArchive.doc", refers only to the name of the entry within the zip archive. A file by that name is not created in the filesystem. The I/O is done strictly with the given streams.
1using (ZipFile zip = ZipFile.Read(InputStream)) 2{ 3 zip.Extract("NameOfEntryInArchive.doc", OutputStream); 4}
Create a zip dynamically within an ASP.NET postback method, then download that zipfile to the requesting browser through Response.OutputStream. This works in DotNetZip v1.5 and later.
1public void btnGo_Click (Object sender, EventArgs e) 2{ 3 Response.Clear(); 4 String ReadmeText= "This is a zip file dynamically generated at " + System.DateTime.Now.ToString("G"); 5 string filename = System.IO.Path.GetFileName(ListOfFiles.SelectedItem.Text) + ".zip"; 6 Response.ContentType = "application/zip"; 7 Response.AddHeader("content-disposition", "filename=" + filename); 8 9 using (ZipFile zip = new ZipFile()) 10 { 11 zip.AddFile(ListOfFiles.SelectedItem.Text, "files"); 12 zip.AddStringAsFile(ReadmeText, "Readme.txt", ""); 13 zip.Save(Response.OutputStream); 14 } 15 16 Response.End(); 17}
Create a zip with a single entry, obtaining the content for that entry from a string. Attach a comment to that entry. Specify the name of the zip file at the time of save.
1string content = "......whatever...."; 2using (ZipFile zip = new ZipFile()) 3{ 4 ZipEntry e = zip.AddEntry("README.txt", content); 5 e.Comment = "This entry in the zip archive was created from a string."; 6 zip.Save("archive-2008july12.zip"); 7}
Open an existing zip archive and modify it: update one entry, remove another, and rename a third. Update the comment on the archive as well.
1using (ZipFile zip = ZipFile.Read("ExistingArchive.zip")) 2{ 3 ZipEntry e = zip["README.txt"]; 4 e.RemoveEntry(); 5 6 // for this entry, update the archive with content from the filesystem 7 zip.UpdateItem("Portfolio.doc"); 8 9 // update the filename of an entry 10 e = zip["Table1.jpg"]; 11 e.FileName = "Figure1.jpg"; 12 13 zip.Comment = "This zip archive was updated " + System.DateTime.ToString("G"); 14 zip.Save(); 15}