extracting a complete zipped archive using C#

I struggled with this for many hours, partly because I wanted to use a class native to .Net 2.0, like GZipStream or DeflateStream, but neither one appeared to be able to handle extracting all directories and files from an archive rather than one single file.  So I ended up using SharpZipLib, which seems to work nicely.  Here's a code sample if you're looking to decompress an archive with more than just one file (don't forget "using ICSharpCode.SharpZipLib.Zip;"):

   public void ExtractAll() {

      // uncompress repository

      String zippedPath = @"C:\test\archive.zip";

      StringBuilder newPath = new StringBuilder(@"C:\test\extraction_test\");

      ZipInputStream zipIn = new ZipInputStream(File.OpenRead(zippedPath));

      DecompressArchive(newPath, zipIn);

   }

   private void DecompressArchive(StringBuilder newPath, ZipInputStream zipIn) {

      ZipEntry entry;

      while ((entry = zipIn.GetNextEntry()) != null) {

         if (entry.Name.EndsWith("/")) {

            Directory.CreateDirectory(String.Format("{0}{1}", newPath, entry.Name.Replace(@"/", @"\")));

         }

         else {

            FileStream streamWriter = File.Create(String.Format("{0}{1}", newPath, entry.Name.Replace(@"/", @"\")));

            long size = entry.Size;

            byte[] data = new byte[size];

            while (true) {

               size = zipIn.Read(data, 0, data.Length);

               if (size > 0) streamWriter.Write(data, 0, (int)size);

               else break;

            }

            streamWriter.Close();

         }

      }

   }

Print | posted on Friday, February 09, 2007 5:18 PM

Comments on this post

# re: extracting a complete zipped archive using C#

Requesting Gravatar...
Very good sample. thanks
Left by jalal on Feb 24, 2007 8:03 AM

# re: code for extracting file in c#

Requesting Gravatar...
i want the code for extracting file specially btr image file.
btr(betrival database file)contains many jpg files so i want to decompress this file
please give me the code for this articles
Left by Mehul sheth on Mar 28, 2007 6:20 AM

Your comment:

 (will show your gravatar)
 
Please add 6 and 7 and type the answer here: