SharpZipLib Examine and select contents of a ZIP file

DukeOfMarmalade picture DukeOfMarmalade · Nov 29, 2011 · Viewed 7.5k times · Source

I am using SharpZipLib in a project and am wondering if it is possible to use it to look inside a zip file, and if one of the files within has a data modified in a range I am searching for then to pick that file out and copy it to a new directory? Does anybody know id this is possible?

Answer

Hans picture Hans · Nov 29, 2011

Yes, it is possible to enumerate the files of a zip file using SharpZipLib. You can also pick files out of the zip file and copy those files to a directory on your disk.

Here is a small example:

using (var fs = new FileStream(@"c:\temp\test.zip", FileMode.Open, FileAccess.Read))
{
  using (var zf = new ZipFile(fs))
  {
    foreach (ZipEntry ze in zf)
    {
      if (ze.IsDirectory)
        continue;

      Console.Out.WriteLine(ze.Name);            

      using (Stream s = zf.GetInputStream(ze))
      {
        byte[] buf = new byte[4096];
        // Analyze file in memory using MemoryStream.
        using (MemoryStream ms = new MemoryStream())
        {
          StreamUtils.Copy(s, ms, buf);
        }
        // Uncomment the following lines to store the file
        // on disk.
        /*using (FileStream fs = File.Create(@"c:\temp\uncompress_" + ze.Name))
        {
          StreamUtils.Copy(s, fs, buf);
        }*/
      }            
    }
  }
}

In the example above I use a MemoryStream to store the ZipEntry in memory (for further analysis). You could also store the ZipEntry (if it meets certain criteria) on disk.

Hope, this helps.