The Wrecking Bawl

Destructuring query language, one keyword at a time.


News


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();

         }

      }

   }

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Comments

Gravatar # re: extracting a complete zipped archive using C#
Posted by jalal on 2/24/2007 8:03 AM
Very good sample. thanks
Gravatar # re: code for extracting file in c#
Posted by Mehul sheth on 3/28/2007 6:20 AM
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
Gravatar # re: extracting a complete zipped archive using C#
Posted by web development company on 8/20/2009 5:01 AM
Cool,
I would have first used ZipStream or DeflateStream as well , i'm happy that I first searched the internet befor writing the wrong code


Thanks for writing, most people don't bother.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: